JSON Web Tokens, or JWTs, are compact and self-contained data structures that serve as a means of transmitting information securely between parties. A JWT consists of three parts: a header, a payload, and a signature. These components are Base64 encoded and concatenated with dots (e.g., xxxxx.yyyyy.zzzzz).

  1. Header: Contains the type of token (JWT) and the signing algorithm used.
  2. Payload: Carries the claims, or user information, that need to be transferred. These claims can include user identification, access rights, and other relevant data.
  3. Signature: The signature is generated using the header, payload, and a secret key. It is used to verify the integrity of the token and ensure that it hasn’t been tampered with.

Decentralized Authentication with JWTs

Traditional centralized authentication methods store user credentials on a central server, which can be vulnerable to single points of failure and security breaches.

Here the auth service generates the session token for an user and stores it in the database so that it can be used by other services to verify the user.

Decentralized authentication, on the other hand, eliminates this risk by distributing the authentication process across various trusted parties.

Using JWTs we can eliminate the need to store them in database entirely. The other services can use the secret used to generate the JWT to validate the user.

Setting JWT Expiry:

The expiration time (exp) is one of the standard claims within the JWT payload. It is represented as a Unix timestamp, indicating the date and time when the token will expire. The expiry value is typically set in the future, allowing the token to be valid for a specific duration, which can range from a few minutes to several hours, depending on the application’s requirements.

Whenever the data is in the hands of the user, security is always a concern. Setting a short but reasonable expiry time is crucial as it prevents misuse of the JWTs and shields against hacks.