PHP code example of zenstruck / jwt

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

    

zenstruck / jwt example snippets


    use Zenstruck\JWT\Token;
    use Zenstruck\JWT\Signer\HMAC\HS256;

    // create the token
    $token = new Token([
        'username' => 'kevin', // custom claim
        'iss' => 'zenstruck', // set issuer
        'exp' => time() + 86400, // set expiry claim to 1 day from now
    ]);

    // can access claims
    $token->get('username'); // kevin
    $token->get('non-existant'); // null

    // sign the token
    $token->sign(new HS256(), 'my secret key');

    $encodedTokenForUser = (string) $token;

    // ...pass to user
    

    use Zenstruck\JWT\Token;
    use Zenstruck\JWT\Signer\HMAC\HS256;
    use Zenstuck\JWT\Validator\ExpiresAtValidator;
    use Zenstuck\JWT\Validator\IssuerValidator;
    use Zenstruck\JWT\Exception\MalformedToken;
    use Zenstruck\JWT\Exception\UnverifiedToken;
    use Zenstruck\JWT\Exception\Validation\ExpiredToken;
    use Zenstruck\JWT\Exception\ValidationFailed;

    $encodedTokenFromUser = // ...fetched from user

    try {
        $decodedToken = Token::fromString($encodedTokenFromUser);
    } catch (MalformedToken $e) {
        // token is not correctly formed
    }

    // at this point $decodedToken is a JWT but is not yet verified or validated

    try {
        $decodedToken->verify(new HS256(), 'my secret key');
    } catch (UnverifiedToken $e) {
        // token could not be verified
    }

    try {
        $decodedToken->validate(new ExpiresAtValidator());
        $decodedToken->validate(new IssuerValidator('zenstruck'));
    } catch (ExpiredToken $e) {
        // the token has expired
    } catch (ValidationFailed $e) {
        // token is invalid - in this case, the issuer does not match
    }

    // can access claims
    $token->get('username'); // kevin
    $token->get('non-existant'); // null
    

use Zenstruck\JWT\TokenBuilder;

$token = (new TokenBuilder())
    ->issuer('kevin')
    ->subject('zenstruck\jwt')
    ->audience('php community')
    ->expiresAt(new \DateTime('+1 day'))
    ->notBefore(new \DateTime('+1 hour'))
    ->issuedAt() // can pass \DateTime object - uses current time by default
    ->id('foo')
    ->set('foo', 'bar') // set custom claims
    ->create(); // instance of Zenstruck\JWT\Token

$token = // ... instance of Zenstruck\JWT\Token
$signer = // an instance of one of the classes in the table above

$token->sign($signer, 'my secret key');
$token->verify($signer, 'my secret key'); // verified
$token->verify($signer, 'invalid secret key'); // unverified - exception thrown

$token = // ... instance of Zenstruck\JWT\Token
$signer = // an instance of one of the classes in the table above
$privateKey = // can be string, resource, filename, instance of Zenstruck\JWT\Signer\OpenSSL\PrivateKey, instance of Zenstruck\JWT\Signer\OpenSSL\Keychain
$publicKey = // can be string, resource, filename, instance of Zenstruck\JWT\Signer\OpenSSL\PublicKey, instance of Zenstruck\JWT\Signer\OpenSSL\Keychain

$token->sign($signer, $privateKey);
$token->verify($signer, $publicKey); // verified
$token->verify($signer, '/path/to/unmatched/public/key'); // unverified - exception thrown

use Zenstruck\JWT\Signer\OpenSSL\Keychain;

$token = // ... instance of Zenstruck\JWT\Token
$signer = // an instance of one of the classes in the table above
$privateKey = // can be string, resource, filename, instance of Zenstruck\JWT\Signer\OpenSSL\PrivateKey
$publicKey = // can be string, resource, filename, instance of Zenstruck\JWT\Signer\OpenSSL\PublicKey

$keychain = new Keychain($publicKey, $privateKey, 'my passphrase');

$token->sign($signer, $keychain);
$token->verify($signer, $keychain); // verified

use Zenstruck\JWT\Validator\IssuerValidator;
use Zenstruck\JWT\Validator\AudienceValidator;
use Zenstruck\JWT\Validator\ChainValidator;

$token = // ... instance of Zenstruck\JWT\Token
$validator = new ChainValidator([new IssuerValidator(), new AudienceValidator()]);

try {
    $token->validate($validator);
} catch (ValidationFailed $e) {
    $reason = $e->getMessage();
}

$validator = (new ValidatorBuilder())
    ->issuer('kevin')
    ->subject('zenstruck\jwt')
    ->audience('php community')
    ->expiresAt()
    ->notBefore()
    ->issuedAt(time())
    ->id('foo')
    ->create(); // instance of Zenstruck\JWT\Validator\ChainValidator