JWT Authentication

JWT Authentication

Why JWT?


When we are working on PHP we can use SESSION for authentication, 

but when we will use API in a third-party application like(iOS, Android, react, etc).

We can't use SESSION. There, JWT will work for authentication.


A JSON Web Token resembles a string divided into three sections by dots. and here is

 header .payload.signature .



Header: This is the first string of JWT.It is a Base64, URL-encoded JSON string, contains information on the token type,

 and the cryptographic algorithm used. eg HMAC SHA256 or RSA.

Payload: This is the second string of JWT. It is a Base64, URL-encoded JSON string, This contains any information you wish to transfer about the user,

 eg the user identifier.

Signature: Signature: Using a digital signature specific to the data in the token, this cryptographic technique is intended to safeguard the JWT's data. 

It uses a hash of the encoded header and payload along with a secret to secure the JWT's data with a digital signature that is specific to the token's contents.


The structure of JWT


eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJ1c2VyX2lkIjoiMjIyIiwiY29tcGFueV9uYW1lIjoib2JqZWN0c29sIn0.ZbOXoRJhQdcJoqKTBu451XvSLoYgzwnWlSDzQp7Yg_A


To secure the PHP, using of JWT


At first we have to install composer on our computer and run the tool from our project folder. 

The Firebase PHP-JWT, a third-party library for interacting with JWT and Apache, will then be installed with the aid of Composer.

Next download JWT library for PHP. Then copy and paste into the working folder. 

We will need to set a login code in login.php. After that we have to put piece of code.


Example piece of code


require("phpjwt/src/BeforeValidException.php");

require("phpjwt/src/CachedKeySet.php");

require("phpjwt/src/JWK.php");

require("phpjwt/src/JWT.php");

require("phpjwt/src/Key.php");

require("phpjwt/src/SignatureInvalidException.php");


use Firebase\JWT\JWT;

use Firebase\JWT\Key;


1. A variable that will hold the secret key, which may be retrieved from the environment files;

2. Another variable to hold information about when the JWT was created.



JWT's can be easily inspected and checked at client-side browsers. 

So it is better to hide secret key and other important information in some environment file, which the user cannot access through client-side requests.


Now that we have all the information required, making a JWT is easy. Here, we'll use the PHP-JWT package's encode() method. This method helps transform our data array into a JSON object.


After transforming the data into a JSON object, the encode function constructs JWT headers and signs the received payload using a cryptographic combination of all the data and the given secret key.


It is essential to supply three arguments to the encode() method to utilize it correctly.

The first argument should be the payload information, which in this case is the data array. The cryptographic technique that the function should employ to sign the JWT must also be specified.


 The first two requirements are to provide the secret key as an input.


As seen below, we must use the echo method instead of the encode method to retrieve and return the JWT.


 if (mysqli_num_rows($result) > 0) {

       $data= mysqli_fetch_assoc($result); 


        $secret_key = 'test123';

        $payload =

         array(

            'email'=>$data['email'],

            'password'=>$data['password']);


        $jwt = JWT::encode($payload, $key, 'HS256');

        $decoded = JWT::decode($jwt, new Key($key, 'HS256'));

         

        echo json_encode(['msg'=>'login success','status' => true, 'emailId'=> $data["email"],'fullName'=> $data["full_name"],'isNotificationAllowed'=>$data["is_notification_allowed"],'id'=> $data["id"],'token'=>$jwt]);

      }


Now that we have the JWT token, we can use any web programming language of our choice to move it to the client-side and save it.Let's start with a short JS demonstration of the route ahead.


First, save the generated and received JWT in client-side memory after a successful form submission. Remove the login form and only provide a button that, when pressed, retrieves and displays the JWT's timestamp to the user to show some output regarding the JWT's success.





Validate Token


To validate the JWT, we must first compare it to the previously created JWT.


The extracted JWT is saved at the first index of the matches array. If the matching array is empty, it means no JWT was extracted. If the preceding code runs successfully, it implies that the JWT has been extracted.


Decoding the received data is required for verifying a JWT. Only the secret key may be used to decode the received data. Once we have obtained the secret key, we may use the static decode function of the PHP-JWT module.


The JWT itself

The algorithm to be used to decode the JWT

If the decode method succeeds, we may proceed to validate the JWT. The code below will assist you in decoding and validating a JWT.


If we check this truogh POSTMAN then have to put the toke in header like this

Authorization : Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJ1c2VyX2lkIjoiMjIyIiwiY29tcGFueV9uYW1lIjoib2JqZWN0c29sIn0.ZbOXoRJhQdcJoqKTBu451XvSLoYgzwnWlSDzQp7Yg_A


<?php

header('Content-Type: application/json');

header('Access-Control-Allow-Methods: POST');

header('Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Authorization, X-Requested-With');


include 'connection.php';

require("phpjwt/src/BeforeValidException.php");

require("phpjwt/src/CachedKeySet.php");

require("phpjwt/src/JWK.php");

require("phpjwt/src/JWT.php");

require("phpjwt/src/Key.php");

require("phpjwt/src/SignatureInvalidException.php");


use Firebase\JWT\JWT;

use Firebase\JWT\Key;


$headers= getallheaders();

$authcode=trim($headers['Authorization']);

$token=substr($authcode,7);

$key = 'test123';

// print_r($token);

try {


$decoded=JWT::decode($token,new Key($key, 'HS256'));

$arr=['msg'=>'Access Allow', 'status'=> 'true', 'Data'=>$decoded];

echo json_encode($arr);

} catch (Exception $e) 

{

$arr=['msg'=>'Access Denied', 'status'=> 'false', 'Data'=>$e->getMessage()];

echo json_encode($arr);

}

?>



This code will provide all the necessary parameters to the decode function and save the method's result. Then, to prevent unauthorized access, error handling is employed. If any of the fields in the JWT are unavailable, an error indicating unauthorized access will be issued to the user.


要查看或添加评论,请登录

Skill Gain的更多文章

  • Do you know how to use Scroll View?

    Do you know how to use Scroll View?

    UIScrollView is a widget or component in UIKit that allows users to scroll through content that is larger than the…

  • Machine Learning

    Machine Learning

    MACHINE LEARNING Machine learning is a field of study that has gained a lot of attention in recent years due to its…

  • CSRF Protection in Flask

    CSRF Protection in Flask

    Let's carry out a quick Flask project to demonstrate how you can manually safeguard your data with CSRF protection. In…

  • Dynamic URLs Variable Rule in Flask

    Dynamic URLs Variable Rule in Flask

    Dynamic URLs Variable Rule in Flask This article will go through Python's Flask-Variable Rule. With no database…

  • Query Parameters with Multi-Value in Flask A

    Query Parameters with Multi-Value in Flask A

    Python-based Flask is a micro-framework. It is well-known for creating RESTful APIs since it is lightweight and simple…

  • Introducing the React Hook for Sound Effects "use-sound"

    Introducing the React Hook for Sound Effects "use-sound"

    Introducing the React Hook for Sound Effects "use-sound" Use the React hook use-sound to play sound effects. This is a…

  • How to Create Spinners In Android?

    How to Create Spinners In Android?

    Android Spinner is a view that resembles a drop-down menu and is used to select a single option from a list of options.…

  • Useful Custom Hooks That You Need To Add Into Your React Project (Part II)

    Useful Custom Hooks That You Need To Add Into Your React Project (Part II)

    Useful Custom hooks that You need to add into your React Project : Hooks are great for extracting logic into reusable…

  • A Brief on React Helmet (Part 1)

    A Brief on React Helmet (Part 1)

    React Helmet Every website developer hopes that his or her website will show up first in the browser's search results…

  • Creating Custom cli Commands in Flask

    Creating Custom cli Commands in Flask

    Creating Custom cli Commands in Flask The focus of this post is on using flask to build custom commands. Run is…

社区洞察

其他会员也浏览了