How to use Firebase/PHP-JWT?
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.
1. Setup a project folder:
First setup a new php project folder where we demonstrate the utilization of firebase/php-jwt.
There for go to your localhsot directory (htdocs
or www
), and create a new folder with any name you wish, I have named this folder php-jwt
for simplicity.
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 installed Composer on your system, you can download and install it from https://getcomposer.org/. Then after in your project directory terminal, run the following command:
composer require firebase/php-jwt
After successfully installing firebase/php-jwt
you can see, the vendor
folder and composer.json
file has been generated.
php-jwt/
├── vendor/
├── composer.json
└── composer.lock
3. Using the firebase/php-jwt library:
Now we will see how to use this firebase/php-jwt library:
For the demonstration we will create three files to separate the script as per its functionality and this will help in better understanding.
So therfore, create the following three php files at the root of the php-jwt
folder:
JwtHandler.php
generate_token.php
decode_token.php
php-jwt/
├── vendor/
├── composer.json
├── composer.lock
├── JwtHandler.php
├── generate_token.php
└── decode_token.php
"JwtHandler.php"
This file will conatin a class called JwtHandler
whcih will be responsible for encoding (signing) and decoding (verifying) JWT tokens using the firebase/php-jwt library.
Here is the code for the JwtHandler.php
(Read the comments to understand):
<?php
# JwtHandler.php
// 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();
}
}
}
"generate_token.php"
The generate_token.php
file will contain php code for generating a new JSON Web Token (JWT).
Basically in this file we will create an object
of the JwtHandler
class and then we will use the encode
method to generate a new token.
<?php
# generate_token.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";
"decode_token.php"
The following code is for decoding the generated JSON Web Token (JWT).
- You should first generate a JWT with the help of the
generate_token.php
. - Then assing the generated JWT to the
$token
variable which located in thedecode_token.php
. - Now if you run the script (
decode_token.php
), it will verify 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);
4. Testing of the JWT Implementation with PHP:
This is the tutorial of how to use Firebase/JWT with PHP. To learn how to implement JWT Authentication in a PHP project, see this - How to build Login and Registration RESTful API in PHP.