Tell me about Spring Security: filter chain, SecurityContext, JWT authentication.
sobes.tech AI
Answer from AI
Spring Security is built around a filter chain that intercepts HTTP requests and processes them sequentially. Each filter is responsible for a specific aspect of security, such as authentication, authorization, CSRF protection, etc.
SecurityContext is an object that stores information about the currently authenticated user (Principal) and their authorities (GrantedAuthorities). It is usually stored in SecurityContextHolder and is accessible during the request processing.
JWT authentication in Spring Security is typically implemented through a special filter that extracts the JWT from the Authorization header, verifies its signature and validity, and then creates an Authentication object with the user's data. This object is placed in the SecurityContext, after which other filters and controllers can use the user's information.
An example of a simplified JWT filter:
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String token = extractToken(request);
if (token != null && validateToken(token)) {
Authentication auth = getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(auth);
}
filterChain.doFilter(request, response);
}
}