PHP code example of vaibhavpandeyvpz / jweety

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

    

vaibhavpandeyvpz / jweety example snippets


use Jweety\Encoder;
use Jweety\Algorithm;

// Initialize encoder with secret key
$encoder = new Encoder('your-secret-key-here');

// Create claims
$claims = [
    'sub' => 'user123',
    'name' => 'John Doe',
    'iat' => time(),
    'exp' => time() + 3600, // Expires in 1 hour
];

// Generate token (defaults to HS256)
$token = $encoder->stringify($claims);
echo $token; // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

use Jweety\Encoder;
use Jweety\Exception\InvalidTokenException;
use Jweety\Exception\TokenExpiredException;
use Jweety\Exception\InvalidSignatureException;

$encoder = new Encoder('your-secret-key-here');

try {
    // Parse and validate token (validates signature and claims by default)
    $claims = $encoder->parse($token);

    echo $claims->sub;    // 'user123'
    echo $claims->name;    // 'John Doe'

} catch (TokenExpiredException $e) {
    // Token has expired
    echo "Token expired: " . $e->getMessage();

} catch (InvalidSignatureException $e) {
    // Signature verification failed
    echo "Invalid signature: " . $e->getMessage();

} catch (InvalidTokenException $e) {
    // Token is malformed or invalid
    echo "Invalid token: " . $e->getMessage();
}

// Parse token without validating claims (exp, iat, nbf)
$claims = $encoder->parse($token, false);

use Jweety\Encoder;
use Jweety\Algorithm;

$encoder = new Encoder('your-secret-key');

// Using enum
$token = $encoder->stringify($claims, Algorithm::HS256);

// Using string
$token = $encoder->stringify($claims, 'HS384');

// Using HS512
$token = $encoder->stringify($claims, Algorithm::HS512);

use Jweety\Encoder;
use Jweety\Algorithm;

// Only allow HS256
$encoder = new Encoder('your-secret-key', Algorithm::HS256);

// Allow multiple algorithms
$encoder = new Encoder('your-secret-key', [Algorithm::HS256, Algorithm::HS384]);

// Using strings
$encoder = new Encoder('your-secret-key', ['HS256', 'HS512']);

use Jweety\Encoder;
use Samay\FrozenClock; // or any PSR-20 Clock implementation

// Create a frozen clock for testing
$clock = new FrozenClock(new \DateTimeImmutable('2024-01-01 12:00:00'));
$encoder = new Encoder('your-secret-key', [Algorithm::HS256], $clock);

// Now all time-based validations use the frozen time
$claims = [
    'sub' => 'user123',
    'exp' => $clock->now()->getTimestamp() + 3600, // 1 hour from frozen time
];

$token = $encoder->stringify($claims);
$parsed = $encoder->parse($token); // Uses frozen clock for validation

$token = $encoder->stringify($claims, Algorithm::HS256, 'CustomType');

use Jweety\Encoder;
use Jweety\Exception\TokenExpiredException;

$encoder = new Encoder('your-secret-key');

// Parse without validation
$claims = $encoder->parse($token, false);

// Manually validate claims
try {
    $encoder->assert($claims);
    echo "Token is valid";
} catch (TokenExpiredException $e) {
    echo "Token expired";
}

$claims = [
    // Subject - The user ID
    'sub' => 'user123',

    // Issued At - When the token was issued
    'iat' => time(),

    // Expiration Time - When the token expires
    'exp' => time() + 3600,

    // Not Before - Token cannot be used before this time
    'nbf' => time(),

    // Issuer - Who issued the token
    'iss' => 'https://example.com',

    // Audience - Who the token is intended for
    'aud' => 'https://api.example.com',

    // JWT ID - Unique identifier for the token
    'jti' => uniqid('', true),

    // Custom claims
    'role' => 'admin',
    'permissions' => ['read', 'write'],
];

$token = $encoder->stringify($claims);

public function __construct(
    #[\SensitiveParameter]
    string $key,
    array|Algorithm|string $algorithms = [Algorithm::HS256, Algorithm::HS384, Algorithm::HS512],
    ?ClockInterface $clock = null
)

public function stringify(
    array|object $claims,
    Algorithm|string $alg = Algorithm::HS256,
    string $typ = 'JWT'
): string

public function parse(string $token, bool $assert = true): object

public function assert(object $claims): void

public static function encode(string $payload): string
public static function decode(string $payload): string

enum Algorithm: string
{
    case HS256 = 'HS256';
    case HS384 = 'HS384';
    case HS512 = 'HS512';

    public function hashMethod(): string;
    public static function values(): array;
}