0

The whole purpose of this is to have a different error message on the frontend when the user is blocked, a different message when the username is not found and when the password is incorrect.

public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                           AuthenticationException exception) throws IOException, ServletException {
        if (exception.getMessage().contains("404")) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } else if (exception.getMessage().contains("disabled")) {
            response.sendError(HttpServletResponse.SC_CONFLICT);
            response.setStatus(HttpServletResponse.SC_CONFLICT);
            response.setHeader("test", "test");
        }
        super.unsuccessfulAuthentication(request, response, exception);
    }
}

I am trying to change the response error status based on the message of the exception.

This class extends the UsernamePasswordAuthenticationFilter and overrides the unsuccessfulAuthentication method. The unsuccessfulAuthentication method is called each time the authentication is unsuccessful.

Even though the response status is set to e.g. conflict, the browser receives 403 unauthorized error.

I don't seem to be able to modify the response status and message/output in any way.

What kind of solution would you recommend to solve this issue?

  • Does this answer your question? [How let spring security response unauthorized(http 401 code) if requesting uri without authentication](https://stackoverflow.com/questions/33801468/how-let-spring-security-response-unauthorizedhttp-401-code-if-requesting-uri-w) – Panagiotis Bougioukos Mar 22 '22 at 15:56
  • From a security standpoint never let the user know if his password is incorrect or his username is not found. – Karim Mar 22 '22 at 16:00
  • @Karim right, right, I know about this, but we want to let the user know – Piotr Chabros Mar 22 '22 at 16:09

1 Answers1

0

I figured it out, I needed to put the "return" keyword before the end of the method.