Customize authentication failure response in Spring Security using AuthenticationFailureHandler

You can add exception handling to you Spring Security by calling .exceptionHandling() on your HttpSecurity object in your configure method.
If you only want to handle just bad credentials you can ignore the .accessDeniedHandler(accessDeniedHandler()).

The access denied handler handles situations where you hav secured you app at method level such as using the @PreAuthorized, @PostAuthorized, & @Secured.

An example of your security config could be like this

SecurityConfig.java
/* 
   The following two are the classes we're going to create later on.  
   You can autowire them into your Security Configuration class.
*/
@Autowired
private CustomAuthenticationEntryPoint unauthorizedHandler;

@Autowired
private CustomAccessDeniedHandler accessDeniedHandler;    

/*
  Adds exception handling to you HttpSecurity config object.
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf()
        .disable()
        .exceptionHandling()
            .authencationEntryPoint(unauthorizedHandler)  // handles bad credentials
            .accessDeniedHandler(accessDeniedHandler);    // You're using the autowired members above.


    http.formLogin().failureHandler(authenticationFailureHandler);
}

/*
  This will be used to create the json we'll send back to the client from
  the CustomAuthenticationEntryPoint class.
*/
@Bean
public Jackson2JsonObjectMapper jackson2JsonObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
    return new Jackson2JsonObjectMapper(mapper);
}   

CustomAuthenticationEntryPoint.java

You can create this in its own separate file. This is Entry point handles the invalid credentials.
Inside the method we’ll have to create and write our own JSON to the HttpServletResponse object. We’ll
use the Jackson object mapper bean we created in the Security Config.

 @Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    private static final long serialVersionUID = -8970718410437077606L;

    @Autowired  // the Jackson object mapper bean we created in the config
    private Jackson2JsonObjectMapper jackson2JsonObjectMapper;

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException e) throws IOException {

        /* 
          This is a pojo you can create to hold the repsonse code, error, and description.  
          You can create a POJO to hold whatever information you want to send back.
        */ 
        CustomError error = new CustomError(HttpStatus.FORBIDDEN, error, description);

        /*
          Here we're going to creat a json strong from the CustomError object we just created.
          We set the media type, encoding, and then get the write from the response object and write
      our json string to the response.
        */
        try {
            String json = jackson2JsonObjectMapper.toJson(error);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
            response.getWriter().write(json);
        } catch (Exception e1) {
            e1.printStackTrace();
        }

    }
}

CustomAccessDeniedHandler.java

This handles authorization errors such as trying to access method without the
appropriate priviledges. You can implement it in the same way we did above with the bad credentials exception.

@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
        AccessDeniedException e) throws IOException, ServletException {

    // You can create your own repsonse here to handle method level access denied reponses..
    // Follow similar method to the bad credentials handler above.
    }

}

Hopefully this is somewhat helpful.

Leave a Comment