Sobes.tech
Junior — Middle

Can you explain the process of checking and granting access to resources via JWT token in Spring Security?

sobes.tech AI

Answer from AI

In Spring Security using JWT, the process of authentication and access granting to resources typically looks like this:

  1. Authentication: the user enters login and password, the server verifies them and, if correct, generates a JWT token containing user information and permissions.

  2. Token transmission: the client saves the token and sends it in the Authorization header (usually Bearer <token>) for subsequent requests.

  3. JWT filter: on the server, a filter is configured to intercept incoming requests, extract the JWT from the header, verify its signature and expiration.

  4. Authentication recovery: if the token is valid, user information (e.g., username and roles) is extracted from it, an Authentication object is created and placed into the SecurityContext.

  5. Authorization: Spring Security uses information from the SecurityContext to check whether the user has access to the requested resource (for example, based on roles).

Example of a simplified filter for JWT verification:

public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String header = request.getHeader("Authorization");
        if (header != null && header.startsWith("Bearer ")) {
            String token = header.substring(7);
            if (jwtUtil.validateToken(token)) {
                String username = jwtUtil.getUsernameFromToken(token);
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(auth);
            }
        }
        filterChain.doFilter(request, response);
    }
}

Thus, JWT provides stateless authentication, allowing the server to verify access rights without storing sessions.