简体   繁体   中英

Change response status onUnsuccessfulAuthentication

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 eg 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?

我想通了,我需要在方法结束之前加上“return”关键字。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM