What is JSON Web Token?

JSON Web Token or JWT is an authorization technique. It is for creating secure web applications.

JWT generally creates a secure way to transfer information between two parties as a JSON object, here the two parties can be a server and a client.

A Token contains the user information along with some more additional information, with this Token we will verify user.

The key difference between Session and Token based authorization is that in Token based, the user information is not store in the server, the user information stored in the token. Then the token stored in the browser, this is why JWT is considered more scalable than session.

In this picture, client makes a post request with { email: email, password: password } to login. The server takes the request then check the email & password then returns a token called JSON Web Token only if email & password both are correct. Then client will store the JWT(token) inside Local Storage or Session Storage or Cookies.

Next time client sends a request with JWT(token) attached to get the response. The server verify the token if the token is correct then the server send the response back to the client.

To identify an authenticated person, you just need to put JSON Web Token in the API end point.

https://www.something.com/users/?token=eyJhbGciOiJIUzI1NiIs.eyJzdWIiOiIxMj.SflKxwRJSMeKKF2Q

Here, eyJhbGciOiJIUzI1NiIs is called header, eyJzdWIiOiIxMj is called payload & SflKxwRJSMeKKF2Q is called signature/crypto.

JWT Structure

A Header is generally consists two parts, type of the token and the hashing algorithm used. For example,

{
  "algo": "HS256",
  "type": "JWT"
}

HS256 signing algorithm being used in the token and type is JWT. Then the header is Base64Url encoded to make first part of the JWT.

The second part of JWT called Payload, the amount of data you want to include into JWT.

{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}

Then the payload is Base64Url encoded to make second part of the JWT.

The last part of JWT is a signature generated based on the Header and Payload. The signature used to verify the JWT is valid or not and the message wasn’t changed along the way.

For example, if you want to use HMAC SHA256 algorithm, the signature will be created in the following order,

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  your-256-bit-secret)

You can encode and decode if you put all together. Go to https://jwt.io/

Leave a Comment

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