Skip to content

Instantly share code, notes, and snippets.

@GaetanoPiazzolla
Created January 30, 2022 19:49
Show Gist options
  • Save GaetanoPiazzolla/9a52a53359b61b09f85939bfa7a398fe to your computer and use it in GitHub Desktop.
Save GaetanoPiazzolla/9a52a53359b61b09f85939bfa7a398fe to your computer and use it in GitHub Desktop.
JWT Interceptor used to authorize requests.
public class JWTInterceptor implements HandlerInterceptor {
@Value("${jwt.key}")
private String jwtKey;
@Autowired
private BlackListingService blackListingService;
@Autowired
private UserRequestScopedBean userRequestScopedBean;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
try {
String token = request.getHeader("Authorization");
token = token.substring(7);
Jwts.parser()
.setSigningKey(Base64.encodeBase64String(jwtKey.getBytes()))
.parseClaimsJws(token);
String blackListedToken = blackListingService.getJwtBlackList(token);
if (blackListedToken != null) {
log.error("JwtInterceptor: Token is blacklisted");
response.sendError(401);
return false;
}
userRequestScopedBean.setJwt(token);
return true;
} catch (Exception e) {
log.error("JwtInterceptor - Exception : {} ",e.getMessage());
response.sendError(401);
return false;
}
}
}
@GaetanoPiazzolla
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment