Skip to main content


JSON Web Token

RFC 7519 -

This is a stateless authentication mechanism as the user state is never saved in server memory. The server's protected routes will check for a valid JWT in the Authorization header, and if it is present, the user will be allowed to access protected resources. As JWTs are self-contained, all the necessary information is there, reducing the need to query the database multiple times.

JWT = JSON Data + Signature source

JWT are self-contained.

What is token-based authentication? This answer lists some advantages (eg CSRF safe):

Anatomy of a JWT: -

Security cheatsheet:

  • Use a random complicated key (JWT Secret) to make brute forcing the token very hard.
  • Don't extract the algorithm from the header. Force the algorithm in the backend (HS256 or RS256).
  • Make token expiration (TTL, RTTL) as short as possible.
  • Don't store sensitive data in the JWT payload, it can be decoded easily.
  • Avoid storing too much data. JWT is usually shared in headers and they have a size limit.


Since anyone can produce a JWT token, the signature is used to verify the authenticity. This way only the server can issue new tokens using the secret.

signature = hash_algorithm(secret, base64urlEncoding(header) + '.' + base64urlEncoding(payload))

JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA. source


RFC 7516 -

JWT are signed and can optionally be encrypted too.

Signed tokens can verify the integrity of the claims contained within it, while encrypted tokens hide those claims from other parties. source

Unless encrypted, the contained information is public, anyone can read/decode it. Hence, do not store sensitive information into it.

If you can decode JWT, how are they secure? -

When JSON Web Tokens are enabled, they are encrypted by default (JWE) with A256GCM




Which algorithm is used to sign.

"alg": "HS256",
"typ": "JWT"


Contains the claims, which can be Registered (ie standard fields), Public (which should be registered in the IANA "JSON Web Token Claims" registry) or Private.

"iat": 1422779638,
"role": "admin"

Eg iat is Issued At Time.


signature = hash_algorithm(secret, base64urlEncoding(header) + '.' + base64urlEncoding(payload))


token = base64urlEncoding(header) + '.' + base64urlEncoding(payload) + '.' + base64urlEncoding(signature)


How Many Days Has It Been Since a JWT alg=none Vulnerability?


Security consultant Tim McLean reported vulnerabilities in some JWT libraries that used the alg field to incorrectly validate tokens, most commonly by accepting a alg=none token. While these vulnerabilities were patched, McLean suggested deprecating the alg field altogether to prevent similar implementation confusion.[10] Still, new alg=none vulnerabilities are still being found in the wild, with four CVEs filed in the 2018-2021 period having this cause.

With proper design, developers can address algorithm vulnerabilities by taking precautions:

  1. Never let the JWT header alone drive verification
  2. Know the algorithms (avoid depending on the alg field alone)
  3. Use an appropriate key size

How I Found An alg=none JWT Vulnerability in the NHS Contact Tracing App -

Store JWT on the client

Also see Authentication#SPA.

If we store it on localStorage we are open to XSS. (Using sessionStorage doesn't make sense since it's cleared when the tab is closed.)

Where to store JWT in browser? How to protect against CSRF? -

Should JWT be stored in localStorage or cookie? -

Do not use it for user sessions

JSON Web Tokens (JWT) are Dangerous for User Sessions—Here’s a Solution -

The biggest problem with JWT is the token revoke problem

Could have stale data

Imagine the user is an admin and got demoted to a regular user with fewer permissions. Again this won’t take effect immediately and the user will continue to be an admin until the token expires.

The state needs to be maintained anyway (for rate-limiting, IP-whitelisting, etc.)

In many real-world apps, servers have to maintain the user’s IP and track APIs for rate-limiting and IP-whitelisting. So you’ll need to use a blazing fast database anyway. To think somehow your app becomes stateless with JWT is just not realistic.

Where can I use it?

There are scenarios where you are doing server-to-server (or microservice-to-microservice) communication in the backend and one service could generate a JWT token to send it to a different service for authorization purposes And other narrow places, such as reset password, where you can send a JWT token as a one-time short-lived token to verify the user’s email.

JWT should not be your default for sessions - -

it’s not needed to have a system for session data, like Redis or a database. All the information is contained in the JWT, it means your infrastructure is in theory simpler. You’re potentially making fewer calls to a data-store on a per-request basis.

cannot 'kill' a session without building complex (and stateful!) infrastructure to explicitly detect and reject them, defeating the entire point of using stateless JWT tokens to begin with.

Why JWTs Suck as Session Tokens -

The way I like to think of JWTs is that they’re just some JSON data that you can verify came from someone you know.

When the server receives a JWT, it can validate that it is legitimate and trust that the user is whoever the token says they are. The server can validate this token locally without making any network requests, talking to a database, etc. This can potentially make session management faster because instead of needing to load the user from a database (or cache) on every request, you just need to run a small bit of local code. This is probably the single biggest reason people like using JWTs: they are stateless.

There are several cases in which JWTs can be useful. If you’re building API services that need to support server-to-server or client-to-server (like a mobile app or single page app (SPA)) communication, using JWTs as your API tokens is a very smart idea.

Ask HN: What's the current sentiment on JWT for stateless auth tokens? -

Why you should not use JWT - -

Major advantage of JWT compared to bearer tokens (or indeed, session authentication) is that they don't require looking up the token. If you have a distributed system, each node in the system can verify JWT correctness for itself and immediately use the data - no need to look up the random string in the database to figure out who it is.

That's great if you've got a true microservices architecture. Your auth service can check user credentials (email and password, or using a 3rd-party auth provider), issue a JWT and call it a day. Other microservices can independently verify the correctness of the token and have the user information immediately, without the need to check in with the auth service. This shaves precious time off of every request handling and lowers the load on your auth service. What's not to like?

Regarding the refresh token:

you've just reintroduced a bearer token, because that's exactly what the refresh token is. Looking at JWTs from that perspective, you've introduced a client-side cache of user identity (the JWT) and added a bunch of complexity (involving the creation, verification, and token refresh) for the hope of optimizing part of the work you used to do on the server (checking user identity using a bearer token). Was it worth it?

JWT vs. Opaque Tokens - -

users can get a token from your authorization server and use it in another without those servers needing to consult a central service.

a self-contained token that is issued is not easy to revoke, but there are a few ways to work around this. For example, you can add an exp claim which signifies an expiration date for the token. Or you can use the jti claim to assign a valid identifier. Using the identifiers, you can create blacklists to block certain token identifiers.

In contrast, opaque tokens are stored on the server. So you can change their contents at will. If a user is banned or deleted, or if any other action is taken that would invalidate their token, you can instantly revoke the token that is residing in your storage. There is no window to use an invalid token.

For this reason, JWT tokens are a bad choice for storing long-lasting authorization and session data. Because of the necessity to include an expiration date with your tokens, you can't really issue them for too long. And if you want to end a session, you can't really make the token invalid.

there are some situations where the self-sufficient nature of JWTs shine. For example, if your system is highly distributed, querying the authorization server for the token details of opaque tokens may create additional internal traffic to the server, increase overall latency, and create a bottleneck for the system.


JavaScript - connect/express middleware that validates a JsonWebToken (JWT) and set the req.user with the attributes - Decode JWT tokens; useful for browser applications. - JWA, JWS, JWE, JWT, JWK, JWKS with no dependencies.