PHP JWT Token Based Authentication

 Hi There, 

In this tutorial you will be learning PHP JWT Token Based Authentication.

What is Authentication?
Authentication is a process of validating users with some keys, token or any other credentials.Authentication is a main concern of the secure application.

What is Token Based Authentication?

Token based authentication is known as session less or stateless because whenever we authenticate any user then we do not need to save any user details on the server side. We simply generate a token that is signed by a secret key and send it to the user to authenticate all secure API calls with the generated token.


What is JWT?

  • JWT stands for JSON Web Token and comprised of user encrypted information that can be used to authenticate users and exchange information between clients and servers.
  • RESTful APIs are stateless. This means that requests from clients should contain all the necessary information required to process the request.
  • If you are building a REST API application using PHP, you are not going to use the $_SESSION variable to save data about the client's session.
  • In order to solve the issue, the client is responsible for persisting the state locally and send it to the sever with each request. 

JWT Structure:

JSON Web Tokens consist of three parts separated by dots (.), which are: 

 
   header.payload.signature
 

Header:

        
        
            "typ""JWT",    
            "alg""HS256"
        }
 

Payload:

  1. Issuer(iss)
  2. Subject (sub)
  3. Audience (aud)
  4. Expiration time (exp)
  5. Issued at (iat)
        
        {
            "sub""user10001",
            "iat"1569302116
        }
 

Signature: 

Signature is most important part of a JSON Web Token(JWT). Signature is calculated by encoding the header and payload using Base64url Encoding and concatenating them with a period separator.

How JWT works?

  • JWT tokens are simply encrypted user's information like identifier, username, email and password.
  • When users are successfully logged in the server, it will produce and send a JWT token back to the client.
  • This JWT token will be persisted by the client using the browser's local storage or cookies and attached with every outgoing request so if the user requests access to certain protected resources, the token needs to be checked first by the server to allow or deny access.
  • php-jwt is a PHP library that allows you to encode and decode JSON Web Tokens (JWT) in PHP, conforming to RFC 7519.


Installation

Use composer to manage your dependencies and download PHP-JWT:

 
    composer require firebase/php-jwt
 

Encoding user information with  PHP-JWT:

     
<?php
    require 'vendor/autoload.php';
    use \Firebase\JWT\JWT;
    header("Content-Type: application/json");
    $secret_key = 'UhpFx:rXt|!TF)IUE0twlzp1^$ZS0d';
    $issuedat_claim = time(); 
    $notbefore_claim = $issuedat_claim + 10
    $expire_claim = $issuedat_claim + 60
    $token = array(
        "iat" => $issuedat_claim,
        "nbf" => $notbefore_claim,
        "exp" => $expire_claim,
        "data" => array(
            "id" => '1',
            "firstname" => 'prabakaran',
            "lastname" => 'palanichamy',
            "email" => 'prabakaranp@hotmail.com'
    ));
    $jwt = JWT::encode($token$secret_key);
    http_response_code(200);
    echo json_encode(
        array(
            "message" => "jwt token created.",
            "jwt" => $jwt,
            "expireAt" => $expire_claim
        ));
    
    ?>
 


Decode JWT:

     
<?php
    require 'vendor/autoload.php';
    use \Firebase\JWT\JWT;
    header("Content-Type: application/json");
    $secret_key = 'UhpFx:rXt|!TF)IUE0twlzp1^$ZS0d';
    $jwt = str_replace('Bearer '''$_GET['Authorization']);
    $decoded  = JWT::decode($jwt$secret_key, ['HS256']);
    echo json_encode(
        array(
            "message" => "jwt token decoded.",
            "jwt" => $decoded
        ));
    ?>



In next tutorial, I will post how to implement JWT Authentication in PHP RESTFul APIS.

Comments