JWT Project - Firebase/Php-JWT - Generating JWT

JWT - JSON Web Tokens

In this project tutorial we will learn to generate JWT or JSON Web Tokens for users using firebase/php-jwt package.

In the introduction tutorial of this project we went through the setup process. Feel free to check that out.

Generating JWT

A JSON Web Token consists of three parts - Header, Payload and Signature.

For this project the header is set to the following.

{
  "typ": "JWT",
  "alg": "HS256"
}

The payload will look something like the following.

{
  "userid": "u1",
  "iat": 1523798197,
  "exp": 1523798257
}

Where, userid stores the userid of the user that logs in.

iat stands for issued at and it is the time at which the JWT was issued.

exp stands for expiration time and it is the time after which the JWT will no longer be valid.

For this project I am using this-is-the-secret as the secret for the JWT signature.

User accounts

To keep things simple I am saving the user details in an array. You can save the details in a database table and retrieve it if you want.

Checkout my jwt-codeigniter-project if you want database involvement and all the other cool stuffs.

Alright, back to this project.

In the following array we have two user accounts.

/**
 * FOR DEMO PURPOSE
 * I have created two accounts
 * Password of the accounts: root1234
 */
$userAccountArr = array(

  array(
    "userid" => "u1",
    "email" => "yusufshakeel@example.com",
    "password" => "$2y$12$3PfY4lNCR62/HH9aNGZFcebloX1gACQIbWeHfTwb8hKhMXfymiNLq",
    "firstname" => "Yusuf",
    "lastname" => "Shakeel"
  ),

  array(
    "userid" => "u2",
    "email" => "user@example.com",
    "password" => "$2y$12$3PfY4lNCR62/HH9aNGZFcebloX1gACQIbWeHfTwb8hKhMXfymiNLq",
    "firstname" => "Example",
    "lastname" => "User"
  )

);

You will find the complete code of this project in my GitHub repository jwt-php-project.

How to generate JWT?

User will enter one of the registered email address and password to login.

If the credentials match we will use the following code to generate JSON Web Token.

$issuedAt = time();
$expirationTime = $issuedAt + 60;  // jwt valid for 60 seconds from the issued time
$payload = array(
  'userid' => $userid,
  'iat' => $issuedAt,
  'exp' => $expirationTime
);
$key = JWT_SECRET;
$alg = 'HS256';
$jwt = JWT::encode($payload, $key, $alg);

Where, $userid variable holds the user ID of the user who logged in.

JWT_SECRET is a constant and it holds the value this-is-the-secret.

We are using HMAC SHA256 hashing algorithm for the signature part of the JWT.

We are using the JWT::encode() method and passing the three arguments $payload, $key and $alg to generate the JWT.

In the above code we are setting the expiration time of JWT to 60 seconds from the issued time. Feel free to change that to whatever you like.

How to validate JWT?

For this we will use the JWT::decode() method.

JWT::decode($jwt, $key, array('HS256'));

In the above code $jwt holds the JSON Web Token value.

$key holds the secret key. And the hashing algorithm used is HMAC SHA256.

The APIs

For this demo project I have created two APIs. The first one is to validate the user login credential and the second one is to fetch the user detail using the JWT issued for the logged in user.

The validation API

For this API we are passing the registered email address and password.

{
  "email": "yusufshakeel@example.com",
  "password": "root1234"
}

The API url is http://localhost/jwt-php-project/api/user and the method is POST.

Your API url may change depending on your development server settings.

On success we will get back the following response from the localhost server.

{
  "code": 200,
  "status": "success",
  "message": "Valid login credentials.",
  "userid": "u1",
  "jwt": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyaWQiOiJ1MSIsImlhdCI6MTUyMzgwMDk0NSwiZXhwIjoxNTIzODAxMDA1fQ.zz4bkTjU5K_RukfHkKjD2t-HvR73RlAsVoPShEW3fN8"
}

The get user detail API

For this API we are passing the JWT value in the URL.

Sample API with the jwt parameter will look like the following.

http://localhost/jwt-php-project/api/user?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyaWQiOiJ1MSIsImlhdCI6MTUyMzgwMDk0NSwiZXhwIjoxNTIzODAxMDA1fQ.zz4bkTjU5K_RukfHkKjD2t-HvR73RlAsVoPShEW3fN8

On success, we will get the following response from the localhost server.

{
  "code": 200,
  "status": "success",
  "data": {
    "userid": "u1",
    "email": "yusufshakeel@example.com",
    "firstname": "Yusuf",
    "lastname": "Shakeel"
  },
  "jwt_payload": {
    "userid": "u1",
    "iat": 1523800945,
    "exp": 1523801005
  }
}

Complete Code

You will find the complete code here.

In the next tutorial we will write some JavaScript to send and receive data from the server via the APIs.

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT