Hello!

I'm using Spring Boot 2.4.5 with Spring Security. When I updated my Spring Boot for the new version, I have a problem with my custom failureHandler, there are not working on my previous onAuthenticationFailure overridden function with response.sendError(). The program does not respond to the error specified by me and sends 302 (redirect to login page). When I use response.setStatus() its works fine, the program sends an error about what I want.

Is it a bug?

My classes utilized on implementation to basic security:

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final RestAuthenticationFailureHandler authenticationFailureHandler;

    public SecurityConfiguration(RestAuthenticationFailureHandler authenticationFailureHandler) {
        this.authenticationFailureHandler = authenticationFailureHandler;
    }

    @Override
    public void apply(HttpSecurity http) throws Exception {
        http.httpBasic()
            .and()
                .formLogin()
                    .loginPage("/login").permitAll()
                    .failureHandler(authenticationFailureHandler);
    }
    ....
}
@Component
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage());
    }
}

Expected behavior Expected a 401 HTTP Status code, but return the 302 HTTP Status code.

Temporary solution:

@Component
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write(exception.getMessage());
        response.getWriter().flush();
    }
}

Comment From: rwinch

@jonathanmdr I believe the problem is that you need to ensure that your error page is made public. Otherwise, sendError is going to trigger a new error dispatch to the error page, Spring Security will intercept it and deny access, and then it will redirect to the form log in page. Using setStatus ensures there is no error dispatch.

Comment From: rwinch

I'm going to close this as it feels like this is a question that would be better suited to Stack Overflow. As mentioned in Getting Support, we prefer to use GitHub issues only for bugs and enhancements. Feel free to update this issue with a link to the re-posted question (so that other people can find it) or add some more details if you feel this is a genuine bug.