1

I have a pretty normal spring security setup (using spring boot) where all the form login is using a ajax based approach (no redirect, etc), and this is working fine for form login.

For basic authentication I want to now also properly handle failed login attempts, and there seems to be some issues here: I can't rely on ControllerAdvice to catch the exceptions anymore which is fine, I tried a custom BasicAuthenticationEntryPoint to do some changes... but all I could do from there was to change the actual exception being thrown.. it was still not being caught by my controller advice.

So what I'm wondering, I understand that spring security works outside of the spring mvc/advice world, so how can I catch and change the default message that is being sent to the user? (for basic auth, for form/session, this is already working fine..)

mortenoh
  • 255
  • 3
  • 17

1 Answers1

1

You can create a custom authentcation entry point that handles authentication exceptions by implementing the interface AuthenticationEntryPoint

@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

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

        // handle the authentication exception
        // you can return json with Jackson and 
        // write it to the HttpServletResponse.
    }
}

You can then autowire it into your security config class and add the exception handling to you HttpSecurity with .exceptionHandling()

@Autowired
private CustomAuthenticationEntryPoint unauthorizedHandler;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .exceptionHandling() 
            .authenticationEntryPoint(unauthorizedHandler);
            // ... the rest of your configuration.
}

You can also find my details at this post.

Customize authentication failure response in Spring Security using AuthenticationFailureHandler

HttpSecurity doc

http://docs.spring.io/spring-security/site/docs/current/apidocs/org/springframework/security/config/annotation/web/builders/HttpSecurity.html


EDIT:

Handling AuthenticationException will handle invalid credentials.

Handling AccessDeniedException handles method level security such as securing a method for specific roles or authorities.

Community
  • 1
  • 1
Jason White
  • 5,495
  • 1
  • 21
  • 30
  • 2
    Thanks, that works great. I had to add it to `http.httpBasic().authenticationEntryPoint( auth );` also, not sure if that because of my setup or not, but now it works at least. – mortenoh Mar 27 '17 at 06:49