PHP code example of lindelius / php-jwt

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

    

lindelius / php-jwt example snippets


use Lindelius\JWT\Algorithm\HMAC\HS256;
use Lindelius\JWT\JWT;

class MyJWT extends JWT
{
    use HS256;
}

$jwt = MyJWT::create('HS256');

// Include whatever data is lue'];

// Let the JWT expire after 20 minutes (optional, but recommended)
$jwt->exp = time() + (60 * 20);

// Encode the JWT using a key suitable for the chosen algorithm
$encodedJwtHash = $jwt->encode('YOUR_HMAC_KEY');

$decodedJwt = MyJWT::decode($encodedJwtHash);

// The data is available immediately after decode
$field = $decodedJwt->field;
$other = $decodedJwt->other;

// HOWEVER, do NOT forget to verify the data before trusting it
$decodedJwt->verify('THE_SAME_HMAC_KEY');

$decodedJwt->verify('THE_SAME_HMAC_KEY', [

    // Single valid audience
    'aud' => 'https://my-application.tld',

    // Multiple valid issuers
    'iss' => ['Expected Issuer', 'Alternate Issuer'],

]); 

use Lindelius\JWT\Algorithm\RSA\RS256;
use Lindelius\JWT\JWT;

class MyJWT extends JWT
{
    use RS256;
}

$jwt = MyJWT::create('RS256');

use Lindelius\JWT\JWT;

class MyJWT extends JWT
{
    public static $leeway = 60;
}

$availableKeys = [
    'key_1' => 'J5hZTw1vtee0PGaoAuaW',
    'key_2' => '8zUpiGcaPkNhNGi8oyrq',
    'key_3' => 'RfxRP43BIKoSQ7P1GfeO',
];

// Decide which key to use for the JWT
$keyId = 'key_2';

// Include the key ID ("kid") in the JWT's header
$jwt = MyJWT::create('HS256');
$jwt->setHeaderField('kid', $keyId);

$encodedJwt = $jwt->encode($availableKeys[$keyId]);

$decodedJwt = MyJWT::decode($encodedJwt);
$decodedJwt->verify($availableKeys);

composer