PHP sample code to create an authorisation key using JSON Web Tokens (JWT)

We know that API play an important role for connecting or transferring data between different system or application with the server,when we are dealing with customer data one of with biggest issue is the security.we need proper authorization to exchange data between the system. Fortunatily we have JSON Web Tokens(JWT) it helps us to create a authorization key and verify the authorization key. here we are checking out how to create a authorization key using JSON Web Tokens(JWT)in PHP.

Let we check in steps

Steps 1

Download JSON Web Tokens library from below link 
https://jwt.io/     download for PHP

Steps2

Create public key and private key


// Create the keypair
$res=openssl_pkey_new();

// Get private key
openssl_pkey_export($res, $privateKey);

// Get public key
$pubkey=openssl_pkey_get_details($res);
$publicKey=$pubkey["key"];

Step 3

Create a PHP page with below code to generate authorisation key


require_once PROJECT_ROOT.'/php-jwt/src/BeforeValidException.php';
require_once PROJECT_ROOT.'/php-jwt/src/ExpiredException.php';
require_once PROJECT_ROOT.'/php-jwt/src/SignatureInvalidException.php';
require_once PROJECT_ROOT.'/php-jwt/src/JWT.php';
use \Firebase\JWT\JWT;
$token_array=array();
$token_array['time']=time();
$token_array['user_name']="sachin";
$token_array['user_id']="144";
$token_array['mobile']="*********";
$token_array['admin']=false;
$authorisation_key=JWT::encode($token_array, $privateKey, 'RS256');

echo $authorisation_key;

Step 4

Create a PHP page with below code to verify authorisation key


require_once PROJECT_ROOT.'/php-jwt/src/BeforeValidException.php';
require_once PROJECT_ROOT.'/php-jwt/src/ExpiredException.php';
require_once PROJECT_ROOT.'/php-jwt/src/SignatureInvalidException.php';
require_once PROJECT_ROOT.'/php-jwt/src/JWT.php';
use \Firebase\JWT\JWT;
$token_array=array();
$token_array['time']=time();
$token_array['user_name']="sachin";
$token_array['user_id']="144";
$token_array['mobile']="*********";
$token_array['admin']=false;
$decoded = JWT::decode($token, $publicKey, array('RS256'));
print_r((array) $decoded);

My Thought

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

Our Tool : hike percentage calculator