In this article, I will learn about JWT Token with different parts and how it works in authentication and authorization.
JWT Token(JSON Web Token) Introduction
A JWT (JSON Web Token) is a compact, URL-safe method for
representing claims (data) between two parties, often used for authentication
and authorization purposes. It is a token-based authentication mechanism widely
used in modern web applications and APIs.
Key Components of JWT
A JWT consists of three parts:
- Header
- Payload
- Signature
These three parts are separated by dots (.
), forming a structure
like this.
Header.Payload.Signature
1. Header
The header contains metadata about the token, such as the type of token and
the algorithm used to sign it. For example:
{
"alg": "HS256", // Algorithm used for signing (HMAC SHA256)
"typ": "JWT" // Type of token (JWT)
}
2. Payload
The payload contains the claims (data) you want to transmit. Claims are
statements about an entity (typically, the user) and additional metadata. There
are three types of claims:
- Registered claims - Predefined claims like sub
(subject), iat (issued at), exp (expiration), iss (issuer).
- Public claims - Custom claims that you define, e.g.,
user roles or permissions.
- Private claims - Claims that are agreed upon between
two parties (not predefined).
Example
{
"sub": "1234567890", // Subject (user ID)
"name": "John Doe", // User's name
"admin": true, // Custom claim (is user an admin)
"iat": 1516239022 // Issued at (timestamp)
}
3. Signature
The signature is used to verify the token’s authenticity. It is created by
encoding the header and payload, and then signing them with a secret key using
the algorithm specified in the header.
The signature ensures that the token has not been tampered with.
Example
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
JWT Token Structure
A complete JWT might look like this.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
- The first part (eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9) is the header.
- The second part
(eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9) is
the payload.
- The third part (SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c) is the
signature.
How JWT Works in Authentication
JWT is typically used in a stateless authentication mechanism for web
applications, meaning that the server doesn’t need to store session information.
Here’s how it works.
-
User Login - The user provides their credentials (username and password)
to the server.
-
JWT Issuance - If the credentials are valid, the server generates a JWT
containing information about the user (e.g., user ID, role, etc.). This JWT
is sent back to the user.
-
Client Stores JWT - The client stores the JWT (typically in local storage
or cookies) and includes it in subsequent HTTP requests, usually in the
Authorization header as a Bearer token
Authorization: Bearer<jwt-token>
-
JWT Validation - For each request, the server verifies the JWT signature
using the secret key to ensure the token is valid and not tampered with. If
valid, the server extracts the user’s information from the token (such as
user ID and role) and processes the request.
-
Access Control - Based on the information in the token, the server can
determine whether the user has the necessary permissions to access the
resource.
Benefits of JWT
- Stateless - The server doesn’t need to maintain session
data, as the JWT itself contains all the necessary information.
- Compact - JWTs are compact and URL-safe, making them
ideal for use in HTTP headers, URLs, or POST bodies.
- Self-contained - All the information about the user and
their permissions is embedded within the token itself.
- Cross-platform - JWT is language-agnostic and works
well across different systems (e.g., web, mobile).
JWT Use Cases
- Authentication - A common use case for JWT is user
authentication in web and mobile applications.
- Authorization - JWT can include roles and permissions
in its payload, allowing systems to authorize users based on the token’s
contents.
- Secure API Access - Many modern APIs (such as OAuth and
OpenID Connect) use JWT to secure access and authorize requests.
Example Flow
- Login Request - The client sends a request with
credentials (e.g., username and password) to the authentication server.
- Token Issuance - The server verifies the credentials
and issues a JWT containing user information.
- Authenticated Requests - The client stores the JWT and
includes it in the header of all future requests to access protected routes
or resources.
- Token Validation - Each time a request with a token is
received, the server verifies its validity and checks user permissions based
on the token.
Security Considerations
- Keep the secret key safe - If the secret key used to
sign the token is compromised, anyone could forge valid tokens.
- Token expiration - Always set an expiration (
exp
)
claim to avoid long-lived tokens.
- Use HTTPS - Always send JWT tokens over HTTPS to
prevent token interception.
- Refresh tokens - Implement refresh tokens for long
sessions so users don't need to log in frequently, but tokens are still
refreshed regularly for security.
Prev
Next