PHP code example of daycry / jwt

1. Go to this page and download the library: Download daycry/jwt 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/ */

    

daycry / jwt example snippets


$psr4 = [
    'Config'      => APPPATH . 'Config',
    APP_NAMESPACE => APPPATH,
    'App'         => APPPATH,
    'Daycry\JWT' => APPPATH .'ThirdParty/JWT/src',
];



namespace Config;

use Daycry\JWT\Config\JWT as BaseJWT;

class JWT extends BaseJWT
{
    public ?string $uid = null;
    public string $signer = 'your-secret-key-base64';
    public string $issuer = 'https://your-domain.com';
    public string $audience = 'https://your-domain.com';
    public string $identifier = 'unique-app-id';
    public string $canOnlyBeUsedAfter = '+0 minute';
    public string $expiresAt = '+24 hour';
    public string $algorithm = \Lcobucci\JWT\Signer\Hmac\Sha256::class;
    public bool $throwable = true;
    public bool $validate = true;
    
    public array $validateClaims = [
        'SignedWith',
        'IssuedBy', 
        'ValidAt',
        'IdentifiedBy',
        'PermittedFor',
    ];
}



namespace Config;

use Daycry\JWT\Config\JWT as BaseJWT;

class JWT extends BaseJWT
{
    public ?string $uid = null;
    public string $signer = 'your-secret-key-base64';
    public string $issuer = 'https://your-domain.com';
    public string $audience = 'https://your-domain.com';
    public string $identifier = 'unique-app-id';
    public string $canOnlyBeUsedAfter = '+0 minute';
    public string $expiresAt = '+24 hour';
    public string $algorithm = \Lcobucci\JWT\Signer\Hmac\Sha256::class;
    public bool $throwable = true;
    public bool $validate = true;
    
    public array $validateClaims = [
        'SignedWith',
        'IssuedBy', 
        'ValidAt',
        'IdentifiedBy',
        'PermittedFor',
    ];
}



// Create JWT instance
$jwt = new \Daycry\JWT\JWT();

// Encode data
$token = $jwt->encode(['user_id' => 123, 'role' => 'admin']);

// Decode and validate
$claims = $jwt->decode($token);
$userId = $claims->get('data'); // Default parameter name



$config = config('JWT');
$config->uid = 'user_123';
$jwt = new \Daycry\JWT\JWT($config);

$token = $jwt->encode(['action' => 'login']);
$claims = $jwt->decode($token);

echo $claims->get('uid'); // user_123



$jwt = (new \Daycry\JWT\JWT())->setParamData('payload');
$token = $jwt->encode(['user' => 'john']);

$claims = $jwt->decode($token);
echo $claims->get('payload'); // JSON string of data



$data = ['name' => 'John', 'role' => 'admin'];
$token = $jwt->encode($data);

$claims = $jwt->decode($token);
$originalData = json_decode($claims->get('data'), true);



$jwt->setSplitData(true);
$data = ['name' => 'John', 'role' => 'admin'];
$token = $jwt->encode($data);

$claims = $jwt->decode($token);
echo $claims->get('name'); // John
echo $claims->get('role'); // admin



$jwt = new \Daycry\JWT\JWT();
$token = $jwt->encode(['user_id' => 123]);

// Fast validation without full decoding
if ($jwt->isValid($token)) {
    echo "Token is valid!";
}



// Extract claims without validation (2x faster)
$claims = $jwt->extractClaimsUnsafe($token);
$userId = $claims['uid'] ?? null;

// Use when you trust the token source



// Quick expiry check
if ($jwt->isExpired($token)) {
    return response('Token expired', 401);
}

// Get time to expiry in seconds
$timeLeft = $jwt->getTimeToExpiry($token);
if ($timeLeft < 300) { // Less than 5 minutes
    // Trigger refresh logic
}



$config = config('JWT');

// All constraints (default)
$config->validateClaims = [
    'SignedWith',   // Verify signature
    'IssuedBy',     // Verify issuer
    'ValidAt',      // Verify time constraints
    'IdentifiedBy', // Verify token ID
    'PermittedFor', // Verify audience
];

// Minimal validation (performance focused)
$config->validateClaims = ['SignedWith'];

// Disable validation entirely (not recommended for production)
$config->validate = false;



// Symmetric algorithms (recommended)
$config->algorithm = \Lcobucci\JWT\Signer\Hmac\Sha256::class; // Default
$config->algorithm = \Lcobucci\JWT\Signer\Hmac\Sha384::class;
$config->algorithm = \Lcobucci\JWT\Signer\Hmac\Sha512::class;



// In your controller or anywhere in CI4
$jwt = service('jwt'); // If you implement the Services.php
$token = $jwt->encode(['user_id' => auth()->id()]);



// Quick encoding
$token = jwt_encode(['user_id' => 123]);

// Quick decoding
$claims = jwt_decode($token);

// Current user ID from JWT
$userId = jwt_user_id();

// Check if user is authenticated
if (jwt_check()) {
    // User has valid JWT
}



// Short-lived tokens for APIs
$config->expiresAt = '+15 minutes';

// Longer-lived for web sessions
$config->expiresAt = '+2 hours';



// Production configuration
$config->validate = true;
$config->validateClaims = [
    'SignedWith',
    'IssuedBy',
    'ValidAt',
    'IdentifiedBy',
    'PermittedFor',
];



try {
    $claims = $jwt->decode($token);
    // Token is valid
} catch (\Lcobucci\JWT\Validation\RequiredConstraintsViolated $e) {
    // Token validation failed
    return response('Invalid token', 401);
}



$config = config('JWT');
$config->throwable = false;
$jwt = new \Daycry\JWT\JWT($config);

$result = $jwt->decode($token);

if ($result instanceof \Lcobucci\JWT\Validation\RequiredConstraintsViolated) {
    // Handle validation error
    echo $result->getMessage();
} else {
    // Valid claims
    $userId = $result->get('uid');
}
bash
php spark jwt:publish
bash
# Publish configuration file to your app
php spark jwt:publish

# Generate a secure signing key
php spark jwt:key [length]

# Generate key with options
php spark jwt:key 32 --show      # Display key without updating .env
php spark jwt:key --force        # Force overwrite existing key
bash
php benchmark.php
bash
# Generate a secure key using the built-in command
php spark jwt:key

# Generate with custom length (32 bytes = 256 bits)
php spark jwt:key 32

# Just display the key without updating .env
php spark jwt:key --show

# Alternative: Generate using OpenSSL
openssl rand -base64 32

# Or using PHP directly
php -r "echo base64_encode(random_bytes(32)) . PHP_EOL;"