Implementing JWT Blacklist with RedisTokenStore in Spring Security OAuth2
This article explains why JWT is not ideal for logout and token renewal, recommends using a Redis‑backed token store, and provides three Redis‑based blacklist implementations with detailed Java code snippets for extending JwtTokenStore, custom converters, and global filters in Spring Security OAuth2.
Explanation
The author advises against using JWT as a token mechanism because it is stateless and makes logout and token renewal difficult; instead, a mature RedisTokenStore is recommended.
JWT cannot control logout (the JwtTokenStore.removeAccessToken method is empty) and cannot implement token renewal because each refresh generates a different token due to time‑based claims.
OAuth2 officially suggests JWT only for internal management systems where logout and renewal are rarely needed; if logout is required, simply delete the token cookie.
Blacklist Implementation Options
Three Redis‑based blacklist solutions are described:
Create a subclass of ResJwtAccessTokenConverter and implement RedisJwtClaimsSetVerifier to override the verify() method.
Create a subclass of ResJwtAccessTokenConverter and override JWTfaultUserAuthenticationConverter 's extractAuthentication() method to check the jti in Redis.
Implement a global filter that checks Redis for the jti before the authentication process.
The author prefers the third approach for efficiency because the check occurs before the OAuth2 login logic.
Extending JwtTokenStore
For a whitelist you would override storeAccessToken; for a blacklist you override removeAccessToken. The implementation stores the jti as the Redis key and the token as the value.
@Slf4j
public class CustomJwtTokenStore extends JwtTokenStore {
private RedisUtil redisUtil;
public CustomJwtTokenStore(JwtAccessTokenConverter jwtTokenEnhancer, RedisUtil redisUtil) {
super(jwtTokenEnhancer);
this.redisUtil = redisUtil;
}
@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
super.storeAccessToken(token, authentication);
}
@Override
public void removeAccessToken(OAuth2AccessToken token) {
if (token.getAdditionalInformation().containsKey("jti")) {
String jti = token.getAdditionalInformation().get("jti").toString();
int expire = token.getExpiresIn();
if (expire < 0) { expire = 1; }
redisUtil.set(jtiRedisKey(jti), token.getValue(), expire);
}
super.removeAccessToken(token);
}
private String jtiRedisKey(String jti) {
return SecurityConstants.CACHE_EXPIRE_TOKEN_BLACKLIST + ":" + jti;
}
}After storing the token in Redis, the filter checks whether the key exists; if it does, the frontend is informed that the token has been logged out.
Solution 1 – Override verify()
A subclass of ResJwtAccessTokenConverter implements RedisJwtClaimsSetVerifier and checks Redis for the jti. If found, it throws a BusinessException("Invalid token!"), which must be caught in a global exception handler because the underlying JwtAccessTokenConverter.decode() wraps any exception as InvalidTokenException("Cannot convert access token to JSON").
public class RedisJwtClaimsSetVerifier implements JwtClaimsSetVerifier {
@Override
public void verify(Map<String, Object> claims) throws InvalidTokenException {
if (claims.containsKey("jti")) {
String jti = claims.get("jti").toString();
Object value = redisUtil.get(jtiRedisKey(jti));
if (value != null) {
throw new BusinessException("Invalid token!");
}
}
}
private String jtiRedisKey(String jti) {
return SecurityConstants.CACHE_EXPIRE_TOKEN_BLACKLIST + ":" + jti;
}
}The author notes that this approach is not ideal because the custom exception is swallowed by the JWT decoder.
Solution 2 – Override extractAuthentication()
Another subclass, JWTfaultUserAuthenticationConverter, checks Redis inside extractAuthentication() and throws InvalidTokenException("Invalid token!") when the token is blacklisted. This method is slightly more reasonable but still incurs performance overhead.
public class JWTfaultUserAuthenticationConverter extends DefaultUserAuthenticationConverter {
@Override
public Authentication extractAuthentication(Map<String, ?> map) {
if (map.containsKey("jti")) {
String jti = (String) map.get("jti");
Object value = redisUtil.get(jtiRedisKey(jti));
if (value != null) {
throw new InvalidTokenException("Invalid token!");
}
}
// normal extraction logic ...
return null;
}
private String jtiRedisKey(String jti) {
return SecurityConstants.CACHE_EXPIRE_TOKEN_BLACKLIST + ":" + jti;
}
}Solution 3 – Global Filter
The preferred method is a filter that runs before authentication. Two variants are provided: a standard servlet filter and a Spring Cloud Gateway/WebFlux filter.
/**
* Filter that checks Redis for a blacklisted jti before authentication.
*/
@Slf4j
public class LogoutAuthenticationFilter extends OncePerRequestFilter {
@Autowired private RedisUtil redisUtil;
@Autowired private TokenStore tokenStore;
@Autowired private ObjectMapper objectMapper;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String token = request.getHeader("Authorization");
if (Strings.isBlank(token) || !token.startsWith(CommonConstant.BEARER_TYPE)) {
filterChain.doFilter(request, response);
return;
}
String authHeaderValue = AuthUtils.extractToken(request);
OAuth2AccessToken accessToken = tokenStore.readAccessToken(authHeaderValue);
if (accessToken.getAdditionalInformation().containsKey("jti")) {
String jti = accessToken.getAdditionalInformation().get("jti").toString();
Object value = redisUtil.get(jtiRedisKey(jti));
if (value != null) {
ResponseUtil.responseWriter(false, objectMapper, response, "this is Invalid token!", HttpStatus.UNAUTHORIZED.value());
return;
}
}
filterChain.doFilter(request, response);
}
private String jtiRedisKey(String jti) {
return SecurityConstants.CACHE_EXPIRE_TOKEN_BLACKLIST + ":" + jti;
}
}A similar WebFlux filter is provided for Spring Cloud Gateway, using RedisTemplate to query the blacklist.
Conclusion
The article demonstrates practical ways to implement token logout and blacklist functionality in a Spring Security OAuth2 environment, compares three approaches, and provides ready‑to‑use Java code snippets for each method.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
