Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a redirect into a custom Authentication Failure Handler with Spring

Which is the properly way to set a redirect into a custom AuthenticationFailureHandler in Spring?

Is it possible to call a controller?

The code is as follows:

@Component
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
            HttpServletResponse response, AuthenticationException exception)
            throws IOException, ServletException {
        super.onAuthenticationFailure(request, response, exception);

        if (exception.getClass().isAssignableFrom(
                CustomUsernameNotFoundException.class)) {

            // TODO Set the redirect

        }
    }

}
like image 203
vdenotaris Avatar asked Apr 28 '14 13:04

vdenotaris


People also ask

How do I redirect in Spring Security?

By default, Spring Security will redirect after login to the secured ressource you tried to access. If you wish to always redirect to a specific URL, you can force that through the HttpSecurity configuration object. Assuming you are using a recent version of Spring Boot, you should be able to use JavaConfig.

How does spring boot handle authentication exception?

Spring security exceptions can be directly handled by adding custom filters and constructing the response body. To handle these exceptions at a global level via @ExceptionHandler and @ControllerAdvice, we need a custom implementation of AuthenticationEntryPoint.


1 Answers

Try soemthing like this

public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        saveException(request, exception);
        //do your things
        getRedirectStrategy().sendRedirect(request, response, "/page/login?error=Retry");
}
like image 109
Anand Rockzz Avatar answered Sep 20 '22 23:09

Anand Rockzz