Do I need to set security context authentication in spring boot JWT token validation?

Viewed 515

I am writing only the JWT token validation or verification. Say there is an external application X, which connects to our Spring Rest API application Y. User has been authenticated at the application X, through OAuth2 (Open ID). Now, application X will send the OAuth2 access token, as a bearer token, when calling our application Y. All we need at our app Y is to check if it has the bearer token, and verify/validate it.

Being a newbie and learning in Spring, I am not sure if I must set the authentication in the securitycontext. Can I just not validate and move on with filterChain.doFilter(..)

package com.app.security.api_token.filter;
import java.io.IOException;
import java.util.ArrayList;
import com.app.security.api_token.util.JWTUtility;

@Component
public class JwtFilter extends OncePerRequestFilter {

 @Autowired
 private JWTUtility jwtUtility;
 
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    
    String authorization = httpServletRequest.getHeader("Authorization");
    String token = null;
    String userName = null;

    if(null != authorization && authorization.startsWith("Bearer ")) {
        token = authorization.substring(7);
        userName = jwtUtility.getUsernameFromToken(token);
    }

    if(null != userName && SecurityContextHolder.getContext().getAuthentication() == null) {
        
        UserDetails userDetails = new User(userName, null, new ArrayList<>());

        if(jwtUtility.validateToken(token,userDetails)) {
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                    = new UsernamePasswordAuthenticationToken(userDetails,
                    null, userDetails.getAuthorities());

            usernamePasswordAuthenticationToken.setDetails(
                    new WebAuthenticationDetailsSource().buildDetails(httpServletRequest)
            );

            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        }

    }
    filterChain.doFilter(httpServletRequest, httpServletResponse);
}

}

0 Answers
Related