JWT (JSON Web Tokens)

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object.

This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

The Quantum comes with JWToken library, which itself built on base of firebase/php-jwt library allowing easly generate and verify tokens.

  • Header - Algorithm (HMAC, SHA256 or RSA) and Type (JWT)
  • Payload - Claims ( iss (issuer), exp (expiration time), sub (subject), aud (audience), etc.) and custom data
  • Signature - Secret key

To start using the JWToken library first make it available in your controller.

use Quantum\Libraries\JWToken\JWToken;


As the token need to be signed you can create a record like JWT_SECRET in your .env file and assign some random value to it or use the generateSecretKey() static method of JWToken class to generate one.

To create JWT you should do the following sequence of actions:

public function createToken() {
    $key = env('JWT_SECRET');

    $jwtToken = new JWToken($key);

    $jwtToken->setPayload($data = [
        'jti' => uniqid(),      // Json Token Id: an unique identifier for the token
        'iss' => base_url(),    // Issuer
        "aud" => base_url(),    // Audience
        'iat' => time(),        // Issued at: time when the token was generated
        'nbf' => time() + 1,    // Not before
        "exp" => time() + 300,  // Expires after 5 min
        "custom" => "some custom data"
    $jwt = $jwtToken->compose();


Bellow are the supported algorithms to set using the setAlgorithm() method (HS256 by default)

  • HS256 - hash_hmac/SHA256
  • HS512 - hash_hmac/SHA512
  • HS384 - hash_hmac/SHA384
  • RS256 - openssl/SHA256
  • RS384 - openssl/SHA384
  • RS512 - openssl/SHA512

The composed JWT can be sent to client for future interaction between server and client. It's preferable to send the JWT to server via Authorization header.

var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/verify", true);
xhttp.setRequestHeader("Authorization", "Bearer " + jwToken;


Using getAuthorizationBearer() static method of Request class you can handle the JWT like this

$jwToken = Request::getAuthorizationBearer();


To verify the JWT and get the data you will need to use the retrieve() method

public function verifyToken() {
    $key = env('JWT_SECRET');

    $jwt = Request::getAuthorizationBearer();

    $jwtToken = new JWToken($key);

    $data = $jwtToken->retrieve($jwt, ['HS384']);


<< Prev Next >>