PHP code example of iachilles / pjwt

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

    

iachilles / pjwt example snippets


  $claims = ['iat' => time(), 'nbf' => time(), 'exp' => strtotime('+1 day'), 'iss' => 'domain.com', 'uid' => 1];
  $headers = ['alg' => 'HS256', 'typ' => 'JWT'];
  $jws = new Jws($headers, $claims);
  $jws->privateKey = 'YoUr_SeCrEt';
  $jws->sign(); //Returns URL-safe string representation of the digitally signed JWT. This encoded JWT can be sent to a user.
  

  $claims = ['iat' => time(), 'nbf' => time(), 'exp' => strtotime('+1 day'), 'iss' => 'domain.com', 'uid' => 1];
  $headers = ['alg' => 'RS256', 'typ' => 'JWT'];
  $jws = new Jws($headers, $claims);
  $jws->privateKey = 'file:///path/to/private/key.pem'; //Path to the PEM encoded private key.
  $jws->sign(); //Returns URL-safe string representation of the digitally signed JWT. This encoded JWT can be sent to a user.
  

  $jws->privateKey = ['file:///path/to/private/key.pem', 'pAsSwOrd'];
   

  $claims = ['jti' => true, 'iat' => time(), 'nbf' => time(), 'exp' => strtotime('+1 day')];
  $headers = ['alg' => 'RS256', 'typ' => 'JWT'];
  $jws = new Jws($headers, $claims);
  

$encodedJwt = 'abcdef.ghijklm.nopqrstuvw';
$jws = Jws::parse($encodedJwt);
$jws->getPayload()->issuedAt; //Access to the registered JWT claims
$jws->getPayload()->getCustomClaim('user_id'); //Access to the custom claims.
$jws->getHeader()->getAlgorithm(); //Access to the JOSE header parameters.

   $encodedJwt = 'abcdef.ghijklm.nopqrstuvw';
   $jws = Jws::parse($encodedJwt);
   //For symmetric algorithm:
   $jws->privateKey = 'YoUr_SeCrEt';
   //For asymmetric algorithm:
   $jws->certificate = 'file:///path/to/certificate.pem'; //Path to the PEM encoded X.509 certificate.
   $jws->verify(); //TRUE if the signature is valid.
   

   $jws->getPayload()->verify(); //Returns TRUE if the JWT is valid, otherwise it returns a string that contains an error message.
   

   $setJti = function($jti)
   {
        //Writes "jti" value into storage. (E.g. Redis Db)
   };
   //This function must return TRUE if the given value exists in storage, false otherwise.
   $getJti = function($jti)
   {
       //...
   };
   $jws->getPayload()->verify($setJti, $getJti);