For those of you who have not utilized JSON Web Tokens before, they are a URL cordial, token based, validation framework. What’s more, they permit you to handily move data through an encoded JSON payload.

The main advantages of JSON Web Tokens are twofold: you don’t have to utilize meetings or treats to keep up with confirmation among states; and you don’t need to continually call the data set for client data as this can be put away in the token payload.

Every token is separated into three sections and each part is separated by a dot.

  1. Header : This contains information on the token type, usually JWT, and the hashing algorithm used, e.g. HMAC SHA256 or RSA.
  2. Payload : This contains any information you wish to transfer about the user, e.g. the user identifier.
  3. Signature : This secures the token and is a hash of the encoded header and payload, along with a secret.
 // Token structure
 header.payload.signature

 // A real world token
 eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

JWT security is accomplished by means of the mark which is made by hashing the encoded header and payload and protecting this with a mystery simply known to the author.

While getting a token from a client, the creator can then approve the signature by re-hashing the got header and payload with the known mystery and checking its coordinates with the got signature. If anybody somehow happened to alter the header or payload, the marks would not match and validation would fail.

How to Build a JSON Web Token in PHP

On the off chance that you’d prefer to build your own JWT generator or simply become familiar, with regards to that the following guide will help. While the models beneath are composed utilizing PHP, the ideas apply to any language so all developers should think that they are useful. The full content is at the bottom part of this guide.

Create the Header and Payload

To begin, we really want to create header and payload JSON strings. We’ll do this dependent on two arrays which exhibits each stating various claims about the token.

For the header we define the type typ and the algorithm alg claims which are RFC standard claims; for the payload we’ll make our own claim user id.

 // Create token header as a JSON string
 $header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);

 // Create token payload as a JSON string
 $payload = json_encode(['employee_id' => 7127]);

Create Base64Url Header and Payload Strings

Next we encode our $header and $payload JSON strings as Base64Url strings. This is marginally unique to a standard Base64 string and there is no underlying PHP Base64Url technique yet. So we need to do a touch of string supplant wizardry which will supplant + with – ,/with _ and = with ”. This is so the Base64 string is passed inside URLs with next to no URL encoding.

 // Encode Header to Base64Url String
 $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));

 // Encode Payload to Base64Url String
 $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));

Create the Signature

To make the mark we want to utilize the hash_hmac() method available in PHP and use the sha256 calculation. We pass in a concatenated string of the Base64Url encoded header and payload $base64UrlHeader . “.” . $base64UrlPayload. It’s important to note that we have to include the dot “.” between the two strings. We add confidential, preferably a strong one that is longer than twelve characters. The ReallySimpleJWT library implements this standard, however for our model we don’t have to stress. At last, we power the hash_hmac() technique to return the yield as double information.

 // Create Signature Hash
 $signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload,'abC123!',true);

Base64Url Encode the Signature

Once we have created the signature, we simply need to Base64Url encode it as we did with the header and payload.

 // Encode Signature to Base64Url String
 $base64UrlSignature = str_replace(['+', '/', '='],['-', '_', ''],base64_encode($signature));

Create the JSON Web Token

Create the JWT by concatenating the header $base64UrlHeader, payload $base64UrlPayload and signature $base64UrlSignature. Each part of the JWT is separated by a dot “.”

 // Create JWT
 $jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;

 // Output
 eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxMjN9.NYlecdiqVuRg0XkWvjFvpLvglmfR1ZT7f8HeDDEoSx8

For Example:-

 // Create token header as a JSON string
 $header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);

 // Create token payload as a JSON string
 $payload = json_encode(['employee_id' => 7127,'FullName' => 'Akash Makwana']);

 // Encode Header to Base64Url String
 $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));

 // Encode Payload to Base64Url String
 $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));

 // Create Signature Hash
 $signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, 'abC123!', true);

 // Encode Signature to Base64Url String
 $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));

 // Create JWT
 $jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;

 echo $jwt;