JSON Web Token (JWT)

JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. It is a widely adopted standard for securely transmitting information in web applications, especially in scenarios involving user authentication and authorization. JWTs are particularly popular in single-page applications (SPAs), microservices, and mobile apps due to their simplicity and effectiveness.

1. What is a JWT?
JWT stands for JSON Web Token, which is a string that represents a set of claims in a compact and self-contained way. A JWT is typically used for identity verification and securely exchanging information between parties. The token consists of three parts, separated by dots (.):

header.payload.signature

Header: Contains the type of the token (usually “JWT”) and the signing algorithm (e.g., HMAC SHA256 or RSA).

Payload: Contains the claims, which are statements about an entity (typically the user) and additional metadata.

Signature: Ensures the token hasn’t been altered. It’s created by signing the header and payload with a secret or a private key.

Enabling mod_rewrite

JWT authentication offers a robust and efficient mechanism for verifying user identity and granting secure access to protected resources.

A JWT token is composed of three distinct parts:

✔️ Header

✔️ Payload

✔️ Signature

Each component is Base64 encoded to construct the token.

1. Header (metadata)

{
“alg”: “HS256”,
“typ”: “JWT”
}

2. Payload (data)

{
“sub”: “1234567890”,
“name”: “John Doe”,
“admin”: true,
“exp”: 1714000000
}

3. Signature

HMACSHA256(
base64UrlEncode(header) + “.” + base64UrlEncode(payload),
secret
)

JWT authentication operates through a straightforward, four-step process.

1 Client (Browser) :

Submits a POST request with credentials to the authentication server for verification and user authentication.

2 Auth Server :

JWT authentication verifies user credentials and generates a JSON Web Token (JWT). The server does not retain any user information; instead, it sends the token to the browser for storage. This approach allows users to authenticate seamlessly in the future without re-entering their credentials. For enhanced security, it is highly recommended to store the token in an HTTP-only cookie.

3 Thereafter :

For each request, the client includes the JWT in the Authorization header. The token is then validated through introspection by the authentication server.

4 Once validated, resource server :

Transfers the required data to the client efficiently.

This provides a foundational understanding of how JWT functions, but there’s a lot more depth to explore.

Enjoy!