spring-bootspring-securityjwtspring-cloud-gatewayspring-filter

Is there any advantage using UserDetailsService of Spring Security, when setting membership with JWT?


I'm applying JWT to authenticate the requests. Parsing and Validating works in my Spring Cloud Gateway. I made a custom filter on SecurityWebFilterChain, which parse and validate the JWT in request header.

I will add this custom filter to ServerHttpSecurity using ServerHttpSecurity.addFilterBefore(myCustomJwtRequestFilter, UsernamePasswordAuthenticationFilter.class).

I want to use SecurityContextHolder.getContext().setAuthentication(authentication) of Spring Security to authenticate the request.

I found that most of examples of it use UserDetails to make Authentication class.

Most of examples I found use UsernamePasswordAuthenticationToken, and I found that it requires UserDetails. To build UserDetails, it essentially requires username, password, roles.

But in my case, I do not want to validate my jwt with User DB every time I got requests. Also, I do not need the password of user since I will not validate it once I generated Token. I want to use only Username and Roles in JWT payload itself.

In summary, I want to make Authentication class only with username and roles and set it authenticated if parsed jwt is validated with my custom method.

It works well with custom userDetails:

UserDetails userDetails = User.builder().username(String.valueOf(parsedInfo.get("username")))
    .authorities(parsedInfo.get("roles")).password("dummypassword").build();

But I have to set Dummy password into it, which I do not need.

I think my solution is not properly applying spring security. But if I won't use UserDetails, is there benefit to use spring security?

Is there any better solution for my case?


Solution

  • If you just need to validate the JWT token then you can use Spring AOP for that.

    @Aspect
    @Component
    public class JwtAspect {
    
        @Before("execution(* com.yourpackageName.* (..))")
        public void checkJwtToken(JoinPoint joinPoint) {
            String jwtTOken = request.getToken();
            if (null == jwtToken) {
                throw new Exception("Token Not Found. ");
            }
            parseToken(jwtToken);
            joinPoint.proceed();
        }
    
    }
    

    If you get the token, parse it and also check the expiry. If above everything works fine, you can proceed your JoinPoint.