Building AI Agent? Test & Secure your AI Agent now. Request access
QA Learning7 min read

What is JWT? JSON Web Token Explained — Structure, Security & Examples

S
Shreya Srivastava
Content Team

What is JWT?

JSON Web Tokens (JWTs) are a standardized way to securely send data between two parties. They contain information (claims) encoded in the JSON format. These claims help share specific details between the parties involved.

At its core, a JWT is a mechanism for verifying the authenticity of some JSON data. This is possible because each JWT is signed using cryptography to guarantee that its contents have not been tampered with during transmission or storage.

It’s important to note that a JWT guarantees data ownership but not encryption. The reason is that the JWT can be seen by anyone who intercepts the token because it’s serialized, not encrypted.

It is strongly advised to use JWTs with HTTPS, a practice that extends to general web security. HTTPS not only safeguards the confidentiality of JWT contents during transmission but also provides a broader layer of protection for data in transit.

A JWT is just a string that looks like this:
xxxxx.yyyyy.zzzzz

It has 3 parts:

  1. Header – says the token type (JWT) and algorithm used (like HS256).

  2. Payload – contains the actual data (like user ID, role, or permissions).

  3. Signature – ensures the token wasn’t changed by anyone.

How Does JWT Work?

How JWT Authentication Works

1. User Logs In

  • A user enters username & password.

  • The server verifies the credentials.

  • If correct, the server creates a JWT containing user info (e.g., userId: 123, role: "admin") and signs it with a secret key.

2. Token Sent to Client

  • The JWT is sent back to the client (usually in a login response).

  • Client stores it safely (localStorage, sessionStorage, or cookies).

3. Client Sends JWT with Requests

  • For every request to a protected API, the client sends the JWT in the Authorization header like this:
    Authorization: Bearer <JWT>

  1. Server Verifies JWT

  • The server receives the token.

  • It checks the signature using the secret key:

    • If valid → it trusts the data inside (like user role).

    • If invalid → rejects the request (401 Unauthorized).

5. Access Granted or Denied

  • If the token is valid and the user has the right permissions, → server allows access.

  • If not, → server denies access.

JWT

Example:

  1. User logs in → gets JWT:
    { "userId": 123, "role": "admin" }

  2. User calls /admin/dashboard with the token.

  3. Server checks role = "admin".

  4. Access granted.

JWT in Microservices, Serverless & Distributed Architectures

In modern distributed or serverless systems, JWTs shine because they eliminate shared session state. You can issue a token once and validate it across services without central session storage.

Best practices in distributed contexts:

  • Use asymmetric signing (RS256 / ES256) so microservices validate without sharing a symmetric secret.

  • Include audience (aud), issuer (iss), jti (JWT ID), and nbf (not before) claims to prevent replay and misuse.

  • Combine short-lived access tokens & refresh token rotation to limit exposure.

This section helps readers see JWT’s real-world scalability and security in distributed systems.

For guidance on token refresh and revocation, see our API Security Checklist

Structure of JWT

The structure of a JWT (JSON Web Token) is made up of three main parts, separated by dots (.):

  1. Header

    • Contains metadata about the token, such as the type of token (JWT) and the signing algorithm used (e.g., HS256, RS256).

    • Example:

  2. Payload

    • Contains the actual data (called claims) that the token carries.

    • Claims can be about the user (like user_id, role) or token metadata (like expiration time).

    • Example:

  3. Signature

  • Created by taking the encoded header + encoded payload, then applying the secret key with the specified algorithm.

  • Ensures that the token hasn’t been tampered with.

  • Formula:

Final JWT looks like this:

  • xxxxx → Encoded Header

  • yyyyy → Encoded Payload

  • zzzzz → Signature

Structure of JWT

JWT example step by step:

  1. Header (before encoding)

After Base64Url encoding →

  1. Payload (before encoding)

After Base64Url encoding →

  1. Signature

We combine:

Base64UrlEncode(Header) + "." + Base64UrlEncode(Payload)

Then hash it with HMACSHA256 and a secret key (e.g., mysecretkey).

Example result:

Final JWT looks like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImV4cCI6MTcxNjAwMDAwMH0.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

JWT

{The first two parts can be decoded back to JSON (header + payload), but the signature can only be verified with the secret key. That’s how JWT ensures integrity and trust.}

Common Attack Scenarios & How to Mitigate Them

Here are common JWT attack vectors and actionable mitigation steps:

Attack / Risk

Description

Mitigation

Token theft (XSS / localStorage access)

Attackers steal JWT stored in client-side JS.

Use HTTP-only cookies, set SameSite flags, and prefer Secure cookies.

Algorithm tampering (“none” attack)

An attacker forces alg = none to bypass signature verification.

Reject tokens with alg: none; whitelist approved algorithms only.

Key confusion / key injection

Using weak or mismatched signing keys.

Use strong cryptographic keys, rotate them regularly, and verify the kid (key ID) in JWT headers.

Replay attacks

Tokens are captured and reused maliciously.

Include a unique jti, validate nbf and exp claims, and maintain a blacklist or store of revoked jti values.

Refresh Tokens, Rotation & Revocation Strategies

JWTs do not inherently support revocation, making token renewal and invalidation critical. Here are strategies to implement safe token refresh and revocation workflows:

  • Refresh token rotation: Issue a new refresh token per request and invalidate the previous one to reduce replay risks.

  • Short-lived access tokens: Use brief expiry (e.g. 5–15 min) and require refresh for continued access.

  • Blacklist / token store: Maintain a lightweight store of revoked jti identifiers to reject compromised tokens.

  • Grace window & reuse detection: Allow a narrow overlap window for refresh but block reuse of old refresh tokens.

This gives developers a clear blueprint for safe token lifecycle management.

Example: Creating & Validating JWT in Python / Go / Java

Benefits of JWT

The main benefits of using JWT (JSON Web Token):

  1. Stateless Authentication

    • JWTs don’t require storing session data on the server.

    • The server just verifies the token, making it scalable and efficient.

  2. Compact and Fast

    • JWTs are small in size (JSON format), so they can be easily sent in headers, URLs, or cookies.

    • This makes them fast to transmit between client and server.

  3. Secure (When Used Correctly)

    • JWTs are signed using algorithms like HMAC or RSA, ensuring data integrity.

    • They can’t be tampered with unless the secret/private key is known.

  4. Cross-Domain / Cross-Platform Support

    • JWTs work well in distributed systems, microservices, and APIs.

    • They can be used across mobile apps, web apps, and different domains.

  5. Self-Contained

    • JWTs carry all the necessary user information (claims) inside the token.

    • This reduces repeated database lookups for authentication.

  6. Flexibility

    • JWTs can store custom data (roles, permissions, expiration time).

    • Useful for access control and fine-grained security.

  7. Widely Adopted

    • JWT is a standard (RFC 7519), supported by many libraries, frameworks, and languages.

In short: JWTs make authentication simpler, faster, and scalable for modern web and mobile applications.

Conclusion

Building and maintaining a proper API inventory and using secure authentication methods like JWT are no longer optional — they’re essential for modern organizations. An updated API inventory gives businesses visibility, improves compliance, and strengthens security by ensuring no API goes unnoticed. At the same time, JWT provides a scalable and secure way to handle authentication, making applications faster and easier to manage.

By combining strong API management with reliable authentication, organizations can protect their digital assets, reduce risks, and improve efficiency. At Qodex.ai, we believe that security and simplicity should go hand in hand — empowering businesses to innovate without compromising safety.


Frequently Asked Questions

What is a JSON Web Token (JWT) and why is it used?

A JSON Web Token, or JWT, is a compact, digitally signed token used to securely transmit information between two parties. It’s widely used for authentication and authorization in web applications because it allows servers to verify user identity without storing session data. JWTs contain encoded claims, like user roles or permissions, helping systems validate access requests efficiently while maintaining stateless communication.

How does JWT authentication work in modern applications?

JWT authentication works by issuing a token after a user successfully logs in. The server encodes key user data and signs it with a secret key before sending it to the client. Each time the client makes a request, it includes the token, allowing the server to verify its authenticity. This stateless process reduces database lookups, improves scalability, and simplifies secure communication between microservices and APIs.

What are the main components of a JWT?

A JSON Web Token is made up of three parts — the Header, Payload, and Signature — separated by dots. The header defines the algorithm used, the payload holds user data or claims, and the signature ensures the token’s integrity using a cryptographic hash. Together, these components make JWTs both lightweight and tamper-resistant, ideal for secure, high-performance authentication in distributed systems.

Is it safe to store JWTs in localStorage or cookies?

Storing JWTs in localStorage or cookies depends on your security model. While localStorage makes token management simple, it exposes tokens to XSS attacks if your site isn’t properly sanitized. Secure, HTTP-only cookies are generally safer as they prevent client-side access. For sensitive applications, pairing cookies with short token lifetimes and refresh tokens enhances JWT security without affecting user experience.

How do JWTs compare to OAuth tokens?

JWTs and OAuth tokens often work together but serve different roles. OAuth is an authorization framework that defines how clients obtain tokens, while JWTs are a token format used within that process. In essence, OAuth provides the rules, and JWT provides the structure. JWT-based OAuth implementations are preferred for modern APIs because they reduce overhead and support seamless, stateless authentication.

What are best practices for securing JSON Web Tokens?

To secure JWTs effectively, always use strong secret keys or asymmetric encryption, validate signatures on every request, and set short expiration times. Avoid storing sensitive data inside payloads, as JWTs are only base64-encoded, not encrypted. Implement token revocation mechanisms and HTTPS to prevent interception. Following these practices ensures JWT-based authentication remains both scalable and compliant with modern API security standards.


Discover, Test, & Secure your APIs 10x Faster than before

Auto-discover every endpoint, generate functional & security tests (OWASP Top 10), auto-heal as code changes, and run in CI/CD - no code needed.