How To Use Firebase JWT With PHP?

Using firebase/php-jwt library in PHP allows you to work with JSON Web Tokens (JWT) in your applications. In ths tutorial, you will learn how to utilizing JWT authentication in PHP using firebase/php-jwt, covering token generation, verification, and decoding.

Step-by-step Guide To Implement Or Use The Firebase JWT

List of Steps #
  1. Create the project folder
  2. Install the firebase/php-jwt library
  3. The JwtHandler.php (class)
  4. Generating JWT Tokens
  5. Verifying and Decoding JWT Tokens
  6. Testing

1. Create the project folder

First, start your localhost then go to the htdocs or www directory, and then create a new folder called php-jwt (You can name this folder whatever you want).

mkdir php-jwt
cd php-jwt

2. Install the firebase/php-jwt library

Navigate to the php-jwt folder and install the firebase/php-jwt library using Composer. If you haven’t already installed Composer, you can download and install it from https://getcomposer.org/. Then, in your project directory, run the following command:

composer require firebase/php-jwt
Installing Firebase JWT via composer

After successfully installing firebase/php-jwt, you can see that the vendor folder and composer.json file has been generated.

PHP JWT folder structure
{
    "require": {
        "firebase/php-jwt": "^6.8"
    }
}

3. The JwtHandler.php (class)

First create a class called JwtHandler.php at root of php-jwt folder. This class is responsible for encoding (signing) and decoding (verifying) JWT tokens using the firebase/php-jwt library.

<?php
// This is JwtHandler.php
require __DIR__ . "/vendor/autoload.php";

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JwtHandler
{
    protected $secrect;
    protected $issuedAt;
    protected $expire;

    function __construct()
    {
        // set your default time-zone
        date_default_timezone_set('Asia/Kolkata');
        $this->issuedAt = time();

        // Token Validity (3600 second = 1hr)
        $this->expire = $this->issuedAt + 3600;

        // Set your strong secret or signature
        $this->secrect = "this_is_my_secrect";
    }

    public function encode($iss, $data)
    {

        $token = array(
            //Adding the identifier to the token (who issue the token)
            "iss" => $iss,
            "aud" => $iss,
            // Adding the current timestamp to the token, for identifying that when the token was issued.
            "iat" => $this->issuedAt,
            // Token expiration
            "exp" => $this->expire,
            // Payload
            "data" => $data
        );

        return JWT::encode($token, $this->secrect, 'HS256');
    }

    public function decode($token)
    {
        try {
            $decode = JWT::decode($token, new Key($this->secrect, 'HS256'));
            return $decode->data;
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }
}

Let’s break down the JwtHandler.php code step by step:

1. Including Dependencies:

require __DIR__ . "/vendor/autoload.php";

This line includes the Composer autoloader file, which loads all the necessary dependencies, including the firebase/php-jwt library.

2. Importing Classes:

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

These lines import the JWT and Key classes from the firebase/php-jwt library. These classes provide functionalities for encoding and decoding JWT tokens.

3. JwtHandler Class Definition:

class JwtHandler
{
    // Class properties
}

This code defines a PHP class named JwtHandler, encapsulating the functionality for encoding and decoding JWT tokens.

4. Constructor Method:

function __construct()
{
    // Set default time-zone
    date_default_timezone_set('Asia/Kolkata');
    // Set issuedAt time
    $this->issuedAt = time();
    // Set token expiration time (1 hour)
    $this->expire = $this->issuedAt + 3600;
    // Set secret key
    $this->secrect = "this_is_my_secrect";
}

In the constructor method, the default time-zone is set to Asia/Kolkata, and the current timestamp ($this->issuedAt) and expiration time ($this->expire) of the token are calculated. Also, a secret key ($this->secrect) is defined for signing the JWT tokens.

5. encode() Method:

public function encode($iss, $data)
{
    // Create token payload
    $token = array(
        "iss" => $iss,
        "aud" => $iss,
        "iat" => $this->issuedAt,
        "exp" => $this->expire,
        "data" => $data
    );
    // Encode token and return
    return JWT::encode($token, $this->secrect, 'HS256');
}

The encode method takes the issuer ($iss) and data to be included in the token ($data) as parameters. It constructs a token payload containing the issuer, audience, issuance timestamp, expiration timestamp, and the provided data. Then, it encodes the payload using the secret key and returns the encoded JWT token.

6. decode() Method:

public function decode($token)
{
    try {
        // Decode token using the secret key
        $decode = JWT::decode($token, new Key($this->secrect, 'HS256'));
        // Return decoded data from token
        return $decode->data;
    } catch (Exception $e) {
        // Return error message if decoding fails
        return $e->getMessage();
    }
}

The decode method takes a JWT token ($token) as input and attempts to decode it using the secret key. If decoding is successful, it returns the decoded data. If decoding fails (due to an invalid token or signature), it returns an error message.

4. Generating JWT Tokens (generate_token.php)

This PHP code is for generating a JSON Web Token (JWT) using a custom class JwtHandler. So, when you run this PHP code, it will output a JWT containing the specified payload and issuer claim.

<?php
require __DIR__ . "/JWTHandler.php";

$jwt = new JwtHandler();

//Payload can be anything you want to store in the token
$payload = "Hi this is Rahul";

$token = $jwt->encode("http://localhost/php-jwt/", $payload);

echo "$token";

5. Verifying and Decoding JWT Tokens (decode_token.php)

The following code is for decoding a JSON Web Token (JWT). You would first generate a JWT using the encode() method defined in the JwtHandler class, then paste that JWT into the $token variable. When you run the script, it will decode the JWT and display the decoded data.

<?php
require __DIR__ . "/JWTHandler.php";

//Add your token which you have generated
$token = "";

$jwt = new JwtHandler();
$data =  $jwt->decode($token);
var_dump($data);

6. Testing

PHP JWT token testing