JWT

Index

  1. What is JWT?
  2. When to use and why?
  3. Application

๐—ช๐—ต๐—ฎ๐˜ ๐—ถ๐˜€ ๐—๐—ช๐—ง?

Securing the API is one of the most important things to do to prevent its abuse. It is done via the authentication and authorisation process and the most used is the ๐—๐—ช๐—ง token-based mechanism.

JSON Web Token is a standard that is used to share information between client and server as a JSON object.

Official Introduction- https://jwt.io/introduction

It is represented as a string that consists of 3 parts: (Memory map JWT[3words 3 parts – H.P.S. – Header Payload Signature])

  1. ๐—›๐—ฒ๐—ฎ๐—ฑ๐—ฒ๐—ฟ: It consists of token type(typ) and signing algorithm that is used(alg). The type will always be JWT, and the signing algorithm can be HMAC SHA256 or RSA.
  2. ๐—ฃ๐—ฎ๐˜†๐—น๐—ผ๐—ฎ๐—ฑ: This part contains related data(mostly for users) known as claims. There are three types of claims:
    • ๐—ฅ๐—ฒ๐—ด๐—ถ๐˜€๐˜๐—ฒ๐—ฟ๐—ฒ๐—ฑ – claims that are recommended to use for interoperability like issuer(iss), subject(sub), expiration time(exp), etc.
    • ๐—ฃ๐˜‚๐—ฏ๐—น๐—ถ๐—ฐ – contains generic information like email, name, or role. Itโ€™s recommended to use collision-resistant names to avoid collision with private claims.
    • ๐—ฃ๐—ฟ๐—ถ๐˜ƒ๐—ฎ๐˜๐—ฒ – custom claims
  3. ๐—ฆ๐—ถ๐—ด๐—ป๐—ฎ๐˜๐˜‚๐—ฟ๐—ฒ: It ensures that the token hasnโ€™t been altered. JWT is signed with the algorithm from a header, and the signature consists of an encoded header and payload, and secret.

A string is always encoded like a Base64 string where every part is separated by dots and like that is easily passed in HTTP environments through HTTP headers.

Note:

  1. the claim names are only three characters long as JWT is meant to be compact.
  2. though signed tokens are protected against tampering, is readable by anyone(base-64 decry-pt). Do not put secret information in the payload or header elements of a JWT unless it is encrypted. (Note – the token is encoded not encrypted)

Relevant articles on encryption vs encoding

Where JWT Is used? (refer official link above for description)

  1. Authorisation
  2. Information exchange

When to use and why?

In cases of S2S cases, no needed to maintain additional tokens for 3rd party.


Application