Video in progress

Senior 🌱 Spring

With JWT, if a user logs out or gets blocked, how do you revoke their token before it expires?

A JWT can't be revoked by itself. You keep the access token lifetime short (5–15 minutes), store refresh tokens on the server and revoke them, and if needed add a denylist by jti/version or introspection.

📖 Answer

The strength of a JWT is that the service checks the signature without going to the database. The weakness is the same thing: the token is valid until it expires, and the server can't "forget" it.

A practical scheme:

  1. A short access token plus a stored refresh token. The access token lives 5–15 minutes. The refresh token is recorded in the database (or Redis); on logout or blocking it is deleted. So in the worst case the user stays in for a few more minutes.

  2. Refresh token rotation. Every refresh issues a new refresh token and the old one is revoked. If an old token is used again, that is a signal it was stolen, and you revoke the whole session family.

  3. If you need immediate revocation (a bank, an admin panel):

  • a denylist by jti in Redis, with TTL = the token's remaining lifetime. One fast lookup per request.
  • Or store a tokenVersion on the user and also inside the token; when blocking, you bump the version.
@Bean
JwtDecoder jwtDecoder(RevokedTokens revoked) {
    NimbusJwtDecoder d = NimbusJwtDecoder.withJwkSetUri(jwkUri).build();
    OAuth2TokenValidator<Jwt> notRevoked = jwt -> revoked.contains(jwt.getId())
        ? OAuth2TokenValidatorResult.failure(new OAuth2Error("invalid_token", "revoked", null))
        : OAuth2TokenValidatorResult.success();
    d.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
        JwtValidators.createDefaultWithIssuer(issuer), notRevoked));
    return d;
}
  1. Opaque token + introspection: every request goes to the auth server. Revocation is immediate, but every call gets an extra network hop; caching the result for 30–60 seconds is the usual compromise.

If you add a denylist, you lose part of the "stateless" advantage, and you should say that openly. I choose by risk level: in an ordinary product a short TTL and refresh revocation are enough; for financial operations immediate revocation is mandatory.