javaspringspring-boot

How to intercept and handle 401 HTTP error in Spring


I am using Spring boot 2.2.9 and i am having a problem getting the entry point for 401 HTTP error, i am trying to change the behavior for my response like we can do with the spring error handler(ResponseEntityExceptionHandler class) for other http errors thanks


Solution

  • To answer this problem: in 2021, for spring security version 5.x.x.

    If you are not using BasicAuthenticationFilter or AbstractAuthenticationFilter and are using your own custom filter for authentication without providing any AuthenticationEntryPoint and you are thinking like I did that unauthenticated user will be automatically be handled by spring security through ExceptionTranslatorFilter, then you are going to be frustrated like me.

    This answer helped me, but the link was not working so here is the updated link of official documentation of current version mentioning this clearly authenticationEntryPont

    So we need to add to configuration this :

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity (prePostEnabled = true)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
          @Override
          protected void configure(HttpSecurity http) throws Exception {
            http.exceptionHandling()
                .authenticationEntryPoint(new MyAuthenticationEntryPoint());
          }
        
        }
    

    Then we implement this class

     public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException authException) throws IOException, ServletException {
               // 401
        }