JWT Explained: How to Decode and Verify a Token Safely
What is a JSON Web Token (JWT)?
A JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. Often used for authentication and authorization in web applications, JWTs allow a server to generate a token that asserts a user's identity or permissions. This token can then be sent to the client, which includes it in subsequent requests to access protected resources. The server can verify the token's integrity and authenticity without needing to query a database every time, making it an efficient method for stateless authentication.
The Structure of a JWT: Header, Payload, and Signature
A JWT is essentially a string divided into three parts, separated by dots (.). Each part is Base64Url-encoded:
header.payload.signature
Let's examine each component in detail.
The JWT Header
The header, the first part of a JWT, is a JSON object that typically contains two fields:
alg: The algorithm used to sign the JWT. Common algorithms include HMAC SHA256 (HS256) or RSA SHA256 (RS256).typ: The type of token, which is usually"JWT".
An example header might look like this:
{
"alg": "HS256",
"typ": "JWT"
}
This JSON is then Base64Url-encoded to form the first part of the JWT string.
The JWT Payload (Claims)
The payload, the second part of the JWT, is also a JSON object. It contains the "claims" – statements about an entity (typically, the user) and additional data. Claims can be categorized into three types:
-
Registered Claims: These are predefined claims that are not mandatory but are recommended for interoperability. Examples include:
iss(issuer): Identifies the principal that issued the JWT.sub(subject): Identifies the principal that is the subject of the JWT.aud(audience): Identifies the recipients that the JWT is intended for.exp(expiration time): Identifies the expiration time after which the JWT MUST NOT be accepted for processing.nbf(not before): Identifies the time before which the JWT MUST NOT be accepted for processing.iat(issued at): Identifies the time at which the JWT was issued.jti(JWT ID): Provides a unique identifier for the JWT.
-
Public Claims: These can be defined by anyone using IANA JSON Web Token Registry or by a URI that contains a collision-resistant name. They should be used with caution to avoid collisions.
-
Private Claims: These are custom claims created to share information between parties that agree to use them. They are not registered or public and should be used within a controlled environment to avoid name collisions.
An example payload might contain user-specific data:
{
"sub": "1234567890",
"name": "John Doe",
"admin": true,
"iat": 1516239022,
"exp": 1516242622
}
This JSON is also Base64Url-encoded to form the second part of the JWT string.
The JWT Signature
The signature is the crucial third part of a JWT, responsible for its integrity and authenticity. It is created by taking the Base64Url-encoded header, the Base64Url-encoded payload, a secret key (for symmetric algorithms like HS256) or a private key (for asymmetric algorithms like RS256), and the algorithm specified in the header, and then signing them.
The general formula for creating a signature is:
signature = Algorithm(Base64UrlEncode(header) + "." + Base64UrlEncode(payload), secret_or_private_key)
For an HS256 (HMAC SHA256) algorithm, the signature would be:
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
your_secret
)
The signature ensures that the token has not been tampered with. If the header or payload is altered, the signature will no longer match, indicating a fraudulent token.
Decoding vs. Verifying a JWT
It's vital to understand the difference between decoding and verifying a JWT:
-
Decoding a JWT: This involves simply Base64Url-decoding the header and payload sections. It allows you to read the information (claims) contained within the token. Anyone with a JWT can decode it, as Base64Url encoding is not encryption. Tools like our JWT Decoder can quickly reveal the token's contents.
{ "alg": "HS256", "typ": "JWT" } . { "sub": "1234567890", "name": "John Doe", "admin": true } . <signature>Decoding alone does NOT guarantee the token's authenticity or integrity. It only extracts the embedded data.
-
Verifying a JWT: This is the process of cryptographically ensuring that the token is legitimate, has not been tampered with, and was issued by a trusted entity. Verification involves:
- Recalculating the signature using the token's header, payload, and the shared secret or public key.
- Comparing the recalculated signature with the signature provided in the token. If they don't match, the token is invalid.
- Validating the claims within the payload (e.g., checking expiration time (
exp), audience (aud), issuer (iss), and 'not before' time (nbf)).
Verification is the cornerstone of JWT security. Without it, a decoded token is meaningless from a security perspective.
Common Security Mistakes When Handling JWTs
While powerful, JWTs can introduce significant security vulnerabilities if not handled correctly. Developers frequently make these mistakes:
1. Not Verifying the Signature
The most critical error. If an application accepts a JWT without verifying its signature, an attacker can simply modify the token's header or payload to grant themselves elevated privileges or impersonate another user. The application would process the modified, unsigned token as valid.
2. Accepting "none" Algorithm in the Header
The JWT standard allows for an "alg": "none" value, meaning the token is not signed. If a server is configured to accept tokens with "alg": "none" without specific checks, an attacker can:
- Change the algorithm to
"none". - Remove the signature entirely.
- Modify the payload to gain unauthorized access.
The server would then process the unsigned, tampered token as valid. Always explicitly whitelist accepted algorithms and reject "none".
3. Not Validating Critical Claims
Even if the signature is verified, failing to validate claims like exp (expiration time), nbf (not before time), aud (audience), and iss (issuer) can lead to issues:
- Expired Tokens: An attacker might reuse an old, expired token if the
expclaim isn't checked. - Incorrect Audience/Issuer: A token issued for a different service or by an untrusted issuer might be accepted, leading to cross-service authentication bypasses.
- Replay Attacks: While JWTs are resistant to simple replay attacks due to expiration, a lack of comprehensive claim validation can still open doors for misuse.
4. Using Weak or Reused Secrets/Keys
The security of HMAC-signed JWTs (like HS256) relies entirely on the secrecy and strength of the shared secret key. If the secret is:
- Too short or simple (e.g., "secret").
- Hardcoded in client-side code.
- Reused across multiple services or environments.
- Compromised due to poor security practices.
An attacker can easily guess or obtain the secret, generate valid signatures for arbitrary payloads, and forge tokens.
5. Not Implementing Token Revocation (Where Necessary)
By design, JWTs are stateless; once issued, they are valid until their expiration. This means that if a user logs out, changes their password, or is banned, an already issued JWT remains valid until it expires. For scenarios requiring immediate invalidation, implementing a token revocation mechanism (e.g., a blacklist/blocklist of compromised or revoked JWT IDs (jti claim) or short expiration times with frequent refresh tokens) is crucial.
Best Practices for Safe JWT Verification
To ensure robust security when working with JWTs, follow these best practices:
1. Always Verify the Signature
This is non-negotiable. Use a trusted JWT library in your chosen programming language to perform signature verification. This library will handle the cryptographic checks correctly.
2. Strictly Validate the Algorithm
Never trust the alg parameter in the header directly. Your application should have a whitelist of acceptable algorithms (e.g., only HS256 or RS256). If the token's alg is not in your whitelist, or if it's "none", reject the token immediately. Most JWT libraries provide configuration options to enforce this.
3. Perform Comprehensive Claim Validation
Beyond signature verification, always validate the following claims:
exp(Expiration Time): Ensure the token has not expired.nbf(Not Before Time): Ensure the token is currently active.iss(Issuer): Verify that the token was issued by a trusted entity.aud(Audience): Confirm the token is intended for your service/application.jti(JWT ID): If you implement token revocation, use this to check against your blacklist.
Many JWT libraries offer built-in functions for claim validation.
4. Use Strong, Unique Secrets or Keys
For symmetric algorithms (e.g., HS256), use long, cryptographically strong, and unique secret keys. Never hardcode them in your application code. Instead, store them securely (e.g., in environment variables, a secret management service, or a Key Management System). For asymmetric algorithms (e.g., RS256), protect your private key diligently and ensure the public key is correctly distributed.
5. Implement Token Revocation (If Needed)
For scenarios requiring immediate invalidation of tokens (e.g., user logout, password change, account disablement), consider strategies like:
- Short-lived tokens with refresh tokens: Short expiration times limit the window of vulnerability. Refresh tokens, used to obtain new access tokens, can be revoked.
- Blacklisting: Store revoked JWT IDs (
jti) in a secure, fast-access blacklist. Check every incoming token'sjtiagainst this list during verification.
Key Takeaways
- JWTs consist of a Base64Url-encoded header, payload, and a signature, separated by dots.
- The header specifies the token type and the signing algorithm.
- The payload carries claims (information) about the entity and additional data.
- The signature ensures the token's integrity and authenticity.
- Decoding a JWT reveals its content but does not verify its legitimacy.
- Verification is critical: it validates the signature and essential claims to ensure the token is authentic, untampered, and currently valid.
- Common security mistakes include not verifying the signature, accepting the "none" algorithm, failing to validate claims, and using weak secrets.
- Always use strong secrets, validate algorithms, perform comprehensive claim checks, and consider revocation strategies for robust JWT security.
Advertisement



