What Is JWT And How It Works

Posted By : Bilal Khan | 30-Apr-2018

JWT-

JSON Web Tokens(JWT) are used for authentication of user credentials. JWT tokens are stateless means there is no need to store cookies and other sessions on the server.

Whenever a user logs in with their credentials. a JWT is returned and saved locally in a local storage of the browser. after that when a logged in user send the subsequent requests to the protected resources on the server it must send JWT token in the header along with the request.

The server receives that request along with JWT token in the header. after receiving JWT server follows series of steps, and if any steps fail then that request is rejected.

Steps required for validation.

1. Check the format of JWT.
2. Check the signature 
3. Verify the claims.
4. Check permissions provided to clients.

In order to understand the working of JWT first, we need understand the Structure of JWT.

Structure:

JWT has three parts which are separated by dots(.) they are as follows.

1. Header
2. Payload
3. Signature.

for example aaaaaaaaa.bbbbbbbbbb.cccccccccc

Let's Understand these parts separately.

1. Header:-

The header has two parts that are the type of the token, which in our case is JWT, and the algorithm for hashing being used, such as HMAC SHA256 or RSA.

Example of Header:

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

2. Payload:

A payload is the second part of JWT, which contains the claims. Claims are just statements about an entity (user) and additional information about that entity.

 JWT defines seven claims that can be included in a token. These are registered claim names, and they are:
Seven claims that are included in the 

1. iss
2. sub
3. aud
4. exp
5. nbf
6. iat
7. jti


Example:

{
  "sub": "1234567890",
  "name": "Bilal Khan",
  "admin": false
}

The payload is converted into  Base64Url encoded to form the second part of the JSON Web Token.

Signature 

To create the signature part that is the third part of the JWT. you have to take the encoded header, payload, a secret and the algorithm specified in the header and sign it.

Example of signature creation.

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)

This signature is used for the verification of the sender. The sender is who it says it is and to confirm that the JWt token information was not changed along the way.

An Example of the generated JWT token is as follows.


eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.(Header)
eyJ1c2VySWQiOiJiMDhmODZhZi0zNWRhLTQ4ZjItOGZhYi1jZWYzZGdmIn0.(Payload)
KFIamt2ZLcoORIHe4yNKZqmzfMxQZsrHORkGcbywgW8I(Signature)

About Author

Author Image
Bilal Khan

Bilal is a Java Developer and has post graduation in M.C.A (IT). Able to handle different types of issues. He loves learning new technologies.

Request for Proposal

Name is required

Comment is required

Sending message..