How To Use Firebase JWT With PHP

JWT implementation using PHP

Using firebase/php-jwt library in PHP allows you to work with JSON Web Tokens (JWT) in your applications. In this step-by-step tutorial, you will learn how to utilize 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

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

Step 1: Create a 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

Step 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"
    }
}

Step 3: Create 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
// JwtHandler.php: This class handles JWT encoding and decoding

// Include required files
require __DIR__ . "/vendor/autoload.php";

// Import JWT class and Key class from Firebase\JWT namespace
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

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

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

        // Define token validity (3600 seconds = 1 hour)
        $this->expire = $this->issuedAt + 3600;

        // Set a strong secret or signature for JWT
        $this->secrect = "this_is_my_secret";
    }

    // Encode JWT
    public function encode($iss, $data)
    {
        // Define token payload
        $token = array(
            "iss" => $iss,      // Adding the identifier to the token (issuer)
            "aud" => $iss,      // Adding the audience to the token (who can use it)
            "iat" => $this->issuedAt,   // Adding the current timestamp to the token
            "exp" => $this->expire,     // Token expiration timestamp
            "data" => $data     // Payload data
        );

        // Encode token using HMAC SHA256 algorithm
        return JWT::encode($token, $this->secrect, 'HS256');
    }

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

Step 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 JWTHandler.php file
require __DIR__ . "/JWTHandler.php";

// Create an instance of JwtHandler class
$jwt = new JwtHandler();

// Define payload to be stored in the token
$payload = "Hi this is Rahul";

// Generate JWT token with issuer and payload
$token = $jwt->encode("http://localhost/php-jwt/", $payload);

// Output the generated token
echo "$token";

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

The following code is for decoding the generated 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 JWTHandler.php file
require __DIR__ . "/JWTHandler.php";

// Add your generated token here
$token = "";

// Create an instance of JwtHandler class
$jwt = new JwtHandler();

// Decode the token to extract data
$data =  $jwt->decode($token);

// Dump the decoded data
var_dump($data);

Step 6: Testing the code

PHP JWT token testing

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy