JSON Web Token - Guide

JSON Web Token - Guide

Table of contents

I was working on a web application and while implementing authentication I came across the term JWTs. So let's understand what it is and how it works.

JSON Web Token (JWT) is a secure way to transmit information between parties as a JSON object. This information is trustworthy because it is digitally signed.

Authorization is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources permitted with that token.

In its compact form, JSON Web Tokens consist of three parts separated by dots (.). Therefore, a JWT typically looks like the following.

xxxxx.yyyyy.zzzzz image

  • Header: The Header contains the information about the token type and the hash algorithm that was used for signing and encoding. In our example, you can see we're using an HS256 hash.

  • Payload: The second part of the token is the payload, which contains the claims.

    • Issuer(iss)
    • Subject (sub)
    • Audience (aud)
    • Expiration time (exp) - in unix timestampt format
    • Issued at (iat) - in unix timestampt format

You can also include custom session data into the payload you want to exchange with the server.

Also, keep in mind that payload can be easily decoded so you mustn't be sending any critical or sensitive data.

  • Signature: Signature is the last and most important part of JWT. Base64url encoding is used to calculate signature by encoding the header and payload and then concatenating them with a period separator.

As you can see, if you change either the header or payload, the signature has to be re-calculated.

If you want to play with JWT and put these concepts into practice, you can use jwt.io Debugger to decode, verify, and generate JWTs.

How do JWT works?

  • The user will sign up with their email/password. This information is received by the Authentication Server.

image

  • The authentication server verifies the email/password combination. If the combination is correct, it will generate the JSON web token. For this, the secret salt or private key can be used. The JWT is returned to the user. image

  • The JWT is usually stored on the client in the session data. For this, cookies or databases can be used.

  • The client can use the generated and stored JWT to access protected data on the server. The client will do this by including the JWT into the HTTP authorization header of every upcoming request it will make to the protected resource. image

Typically in the Authorization header using the Bearer schema.

Authorization: Bearer <token>
  • In the last step, the resource server receives the request with the JWT. It verifies the JSON web token authenticity. If it's correct, it will read the resource and return it to the user.

image

image.png

Did you find this article valuable?

Support Bhavika Tibrewal by becoming a sponsor. Any amount is appreciated!