JWT Basics
Pranav Bakare
Posted on September 9, 2024
Here are the basics of JSON Web Tokens (JWT):
Structure
A JWT consists of three parts, each encoded in Base64Url format, separated by periods (.
):
-
Header: Describes the token type and signing algorithm.
- Example:
{ "alg": "HS256", "typ": "JWT" }
-
Payload: Contains the claims or statements about the user and additional data. Claims are of three types:
-
Registered Claims: Predefined claims like
sub
(subject),iat
(issued at), andexp
(expiration). - Public Claims: Custom claims that can be defined but must be unique to avoid conflicts.
- Private Claims: Custom claims agreed upon by the parties using the token.
- Example:
{ "sub": "1234567890", "name": "John Doe", "iat": 1516239022 }
-
Registered Claims: Predefined claims like
-
Signature: Created by combining the encoded header and payload with a secret key using the specified algorithm (e.g., HMAC SHA256).
- Example:
HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret )
Usage
Authentication: JWTs are often used for authentication, where a server issues a token upon successful login. The client includes this token in subsequent requests, allowing the server to verify the user's identity.
Authorization: JWTs can also be used to grant access to resources. The token may include roles or permissions that determine what the user can access.
Example Flow
- User Login: User logs in, and the server generates a JWT.
- Token Transmission: The server sends the JWT to the client.
-
Client Requests: The client includes the JWT in the
Authorization
header of future requests. - Server Verification: The server verifies the JWT's signature and extracts the claims to process the request.
Security Considerations
- Confidentiality: JWTs are not encrypted by default, so sensitive information should not be included in the payload. For confidentiality, use JWTs with encryption or use HTTPS to protect tokens in transit.
-
Expiration: JWTs should have an expiration (
exp
claim) to limit their validity period and reduce risk if a token is compromised. - Signature: Always verify the signature of the JWT to ensure its authenticity and integrity.
JWTs are useful for their stateless nature, allowing authentication and authorization information to be transmitted securely between parties.
Posted on September 9, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.