JWT For Dummies

What is JWT?

JWT stands for Json Web Token. It is a compact, signed token (string) that represents user’s authenticated identity.

What Problem Does JWT Solve?

You won’t need JWT unless you need a way to solve authentication and authorization for your front-end applications. Storing user’s identity in the browser is prone to risk. Reloading every page in your application to validate user’s identity is bad UX.

Therefore, we need a mechanism to infer user’s identity without exposing the password along with user’s capabilities (authorization) and JWT solves exactly that.

JWT Structure

JSON has three parts — header, payload & signature.

HEADER.PAYLOAD.SIGNATURE

Header describes the type and the signing algorithm that is used.

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

Payload contains the information associated with the token. The standard claims in the payload are: Subject (sub), Issued At (iat), Expiration time (exp), Issuer (iss), Intended audience (aud) & Unique token ID (jti)

{
  "sub": "user_123",
  "role": "doctor",
  "iat": 1791268200,
  "exp": 1791269100
}

In addition to the standard claims, application specific claims can also be included.

{
  "sub": "user_123",
  "role": "doctor",
  "permissions": [
    "patient:read",
    "patient:update"
  ]
}

Signature (Secret_Key) is what prevents someone from changing the token.

HMAC-SHA256(
    base64Url(header) + "." + base64Url(payload),
    SECRET_KEY
)

Here is an useful mental model:

JWT
├── Header
│   ├── alg       ← standard JOSE header parameter
│   └── typ       ← standard JOSE header parameter
│
├── Payload
│   ├── iss       ← standard JWT claim
│   ├── sub       ← standard JWT claim
│   ├── aud       ← standard JWT claim
│   ├── exp       ← standard JWT claim
│   ├── iat       ← standard JWT claim
│   │
│   ├── role      ← your custom claim
│   └── permissions ← your custom claim
│
└── Signature

How JWT Works?

Consider a Node JS application where the server returns a JWT (usually with an expiry of 5-15 mins) to the front-end once user successfully authenticates. When the server returns the JWT, it also sets the refresh token as a HTTP only cookie (Javascript cannot read this value) alongside.

An example JWT token looks like the following:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzEyMyIsInJvbGUiOiJkb2N0b3IifQ.abc123signature

When front-end application makes a request, the refresh token is usually sent along by the browser. The browser decides the cookies to be sent based on domain/path.

On each request, the server receives both the access token ad the refresh token. The server can then check the expiry of the access token and use the refresh token to validate and return a new access token. This is how JWT usually works.

I’m sure you’ve questions regarding JWT. I would be happy to answer them in the comments.

Comments

Leave a Reply

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