PHP code example of plopster / jwt-auth

1. Go to this page and download the library: Download plopster/jwt-auth library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

plopster / jwt-auth example snippets


use JwtAuth\Config\JwtConfig;
use JwtAuth\Claims\DefaultClaimsProvider;
use JwtAuth\Keys\LocalKeyProvider;
use JwtAuth\Services\TokenGenerator;
use JwtAuth\Services\TokenValidator;
use JwtAuth\Services\TokenRefresher;
use JwtAuth\Validation\DefaultClaimValidator;
use JwtAuth\Core\JwtManager;

$config = new JwtConfig(
    issuer: 'my-app',
    audience: 'my-users',
    algorithm: 'RS256',
    privateKeyPath: __DIR__ . '/keys/private.pem',
    publicKeyPath: __DIR__ . '/keys/public.pem',
    ttl: 3600
);

$keyProvider = new LocalKeyProvider($config->privateKeyPath, $config->publicKeyPath);
$claimsProvider = new DefaultClaimsProvider($config->issuer, $config->audience, $config->ttl);
$claimValidator = new DefaultClaimValidator();

$generator = new TokenGenerator($config, $claimsProvider, $keyProvider);
$validator = new TokenValidator($config, $keyProvider);
$refresher = new TokenRefresher($generator);

$jwtManager = new JwtManager($generator, $validator);

// Generate a token
$token = $jwtManager->createToken(['user_id' => 42]);

// Validate the token
$payload = $jwtManager->verifyToken($token);

// Refresh the token
$newToken = $refresher->refresh($payload);