java – Spring Security: how to change HTTP Status for response?


If authorization is unsuccessful, I need to return the 401 status. Since our project uses Spring Security , the authorization setting is configured through it:

        protected void configure(HttpSecurity http) throws Exception {

As we can see, I used failureHandler() to handle the authorization error.

And I wrote a custom handler:

public class CustomAuthFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    private static final String ADMIN_LOGIN = "/admin/login";
    private static final Integer STATUS_UNAUTHORIZED = 401;
    private static final String RESPONSE_CODE_KEY = "Response-Code";
    private static final String RESPONSE_BAD_CREDENTIALS = "bad-credentials";

    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        getRedirectStrategy().sendRedirect(request, response, ADMIN_LOGIN);

Header is sent without problems, but instead of the 401 status, the response is 302. That is, the status I defined is overwritten somewhere. Maybe not need to use sendRedirect ?

Please tell me a working solution within the existing code.


In general, it turned out that you can do either redirection with, say, headers, but without HttpStatus , or add HttpStatus , but without redirects. So that there is both status and redirection, you cannot do it with Spring Security.

I solved the problem as follows: I created another jsp and changed the line in the settings




The same can be done with the help of the handler.

Scroll to Top