Implement token blacklist for JWT logout support
- TokenBlacklistService tracks invalidated tokens using Caffeine cache. - AuthController adds tokens to blacklist on logout. - JwtAuthenticationFilter blocks blacklisted tokens during authentication.
This commit is contained in:
+13
-1
@@ -20,10 +20,14 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
private final JwtService jwtService;
|
||||
private final UserRepository userRepository;
|
||||
private final TokenBlacklistService tokenBlacklistService;
|
||||
|
||||
public JwtAuthenticationFilter(JwtService jwtService, UserRepository userRepository) {
|
||||
public JwtAuthenticationFilter(JwtService jwtService,
|
||||
UserRepository userRepository,
|
||||
TokenBlacklistService tokenBlacklistService) {
|
||||
this.jwtService = jwtService;
|
||||
this.userRepository = userRepository;
|
||||
this.tokenBlacklistService = tokenBlacklistService;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -42,6 +46,14 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
}
|
||||
|
||||
jwt = authHeader.substring(7);
|
||||
|
||||
// Check if token is blacklisted
|
||||
if (tokenBlacklistService.isTokenBlacklisted(jwt)) {
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.getWriter().write("Token has been blacklisted");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
userEmail = jwtService.extractUsername(jwt);
|
||||
} catch (Exception e) {
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.skycrate.backend.skycrateBackend.security;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Service
|
||||
public class TokenBlacklistService {
|
||||
|
||||
private final Cache<String, Boolean> blacklistCache;
|
||||
|
||||
public TokenBlacklistService() {
|
||||
this.blacklistCache = Caffeine.newBuilder()
|
||||
.expireAfterWrite(1, TimeUnit.HOURS)
|
||||
.build();
|
||||
}
|
||||
|
||||
public void blacklistToken(String token) {
|
||||
blacklistCache.put(token, true);
|
||||
}
|
||||
|
||||
public boolean isTokenBlacklisted(String token) {
|
||||
return blacklistCache.getIfPresent(token) != null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user