-2

I am new in Spring and developing a project in Spring Boot 3.1.2 with Spring Security 6.1.2. If the JWT Token is invalid, I am using my customBearerTokenAccessEntryPoint and customBearerTokenAccesDeniedHandler. I also want to handle the exception when the request's authorization type is different from "Bearer Token" (like no auth, basic auth etc.). How can I handle that? I thought I can write another custom entry point and handler for that and use it in security config but I couldn't find the way how can I do that. So if the request's auth. type is different from Bearer Token, other custom entry poind and handler should be executed. If it is Bearer Token and JWT token is invalid customBearerTokenAccessEntryPoint and customBearerTokenAccesDeniedHandler should be executed. If my approach is wrong and I can check this in an easier way, I'd like to know that too. Can you help me in this. Thanks in advance.

CustomBearerAuthenticationEntryPoint:

@Component
public class CustomBearerAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        response.setStatus(401);
        response.setContentType("application/json");
        response.getWriter().write("{\"status\":\"error\",\"message\":\"Invalid JWT token\"}");
    }
}

CustomBearerTokenAccesDeniedHandler:

@Component
public class CustomBearerTokenAccesDeniedHandler implements AccessDeniedHandler {
    private final HandlerExceptionResolver resolver;

    public CustomBearerTokenAccesDeniedHandler(@Qualifier("handlerExceptionResolver") HandlerExceptionResolver resolver) {
        this.resolver = resolver;
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        this.resolver.resolveException(request,response,null,accessDeniedException);
    }
}

My SecurityConfig class:

@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
     http
             .csrf(csrf -> csrf.disable())
             .authorizeHttpRequests(authorize -> {
                 authorize.requestMatchers("/api/projects/getProjects").authenticated();
                 authorize.requestMatchers("/api/activities/getActivities").authenticated();
                 authorize.requestMatchers("/api/participants/getSelectedParticipants").authenticated();
                 authorize.dispatcherTypeMatchers(DispatcherType.ERROR).permitAll();
                 authorize.anyRequest().permitAll();

             })
             .exceptionHandling(exceptionHandling ->
                     exceptionHandling.
                             authenticationEntryPoint(this.customBearerTokenAccessEntryPoint)
                             .accessDeniedHandler(this.customBearerTokenAccesDeniedHandler))
             .sessionManagement(sessionManagement -> sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
             .addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);


     return http.build();
 }

If auth. type is bearer token and jwt token is invalid, the response is:

{
    "status": "error",
    "message": "Invalid JWT Token"
}

If the request's auth. type is different from Bearer Token, the response should be:

{
    "status": "error",
    "message": "myMessage"
}

0 Answers0