Authentication failure redirect with request params not working

spring security redirect on authentication failure
authentication failure-url spring security
spring security log authentication failures
simpleurlauthenticationfailurehandler
spring security invalid credentials
spring boot authentication handler
spring security custom error message
spring boot security error

I am trying to configure my own success and authentication failure handlers. On authentication failure I want to redirect back to my login page with a request parameter, the presence of this parameter will output the error message on my login page. However although on error I am getting redirected back to my login page, the request parameter is always null.

Code below:

protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/login").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login.html").permitAll() 
            .usernameParameter("username")
            .passwordParameter("password")                                               
            .loginProcessingUrl("/login")
            .successHandler(successHandler())
            .failureHandler(handleAuthenticationFailure());
}

@Autowired
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    //database checks
}
};
}

/**
 * Authentication success handler defines action when successfully authenticated
 * @return
 */
@Bean
public AuthenticationSuccessHandler successHandler(){
    return new AuthenticationSuccessHandler() {

        @Override
        public void onAuthenticationSuccess(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Authentication authentication)
                throws IOException, ServletException {

            // custom auth success here
            httpResponse.setStatus(HttpServletResponse.SC_OK);
            SavedRequest savedRequest = (SavedRequest) httpRequest.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST");
            httpResponse.sendRedirect(savedRequest.getRedirectUrl());
        }
    };
}

@Bean
public AuthenticationFailureHandler handleAuthenticationFailure() {
    return new SimpleUrlAuthenticationFailureHandler() {

        @Override
        public void onAuthenticationFailure(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
                                            AuthenticationException authenticationException) throws IOException, ServletException {

            // custom failure code here
            setDefaultFailureUrl("/login.html?error=fail");
            super.onAuthenticationFailure(httpRequest, httpResponse, authenticationException);
        }
    };
}

Try with this:

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

    // .......

    response.sendRedirect("/login.html?error=fail");    
}

Update:

It's really important that the "/login.html?error=fail" is added to an authorizeRequests() section otherwise the controller won't pick up the error parameter.

Replace .antMatchers("/login").permitAll() with .antMatchers("/login**").permitAll()

Spring Security custom authentication failure handler redirect with , I have a problem with Spring Security authentication failure handler redirect with parameter. In security config when I use failureUrl("/login.html? Everything with forms authentication works great except the auto-redirect. If I go directly to logn.aspx, I am able to successfully login, receive the "welcome back" message then I have a response.redirect(request.querystring("returnUrl")) that when clicked simply refreshes login.aspx and now everything is blank white.

Also had problem with params (in my case when login was failed and some request params was added to url it redirected to login page without params).

This solved my problem

.antMatchers("/login**").permitAll()

Redirect after authentication fails to url with query parameters � Issue , Hm I don't think those versions should be a problem. From your original post it looks like there is an issue with either history or the react-router-� I'm not sure if this is also you, but there is a similar thread going on in the AngularFire repo. As mentioned in that issue, we really need a repro to help out here. You say you are using this in a Chrome extension, which is probably not going to work that great. I don't remember the specifics, but I think auth in a Chrome extension does not work.

I'm new in springBoot, if you are using spring boot 2.1.4.RELEASE, try this configuration:

http.csrf().disable()
            .authorizeRequests()
            // URLs matching for access rights
            .antMatchers("/").permitAll()
            .antMatchers("/login").permitAll()
            .anyRequest().authenticated()
            .and()
            // form login
            .formLogin()
            .loginPage("/login")
            .failureUrl("/login?error=true")
            .successHandler(sucessHandler)
            .usernameParameter("email")
            .passwordParameter("password")
            .and()
            // logout
            .logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessUrl("/").and()
            .exceptionHandling()
            .accessDeniedPage("/access-denied");

To use the above-defined Spring Security configuration, we need to attach it to the web application. In this case, we don’t need any web.xml:

public class SpringApplicationInitializer 


extends AbstractAnnotationConfigDispatcherServletInitializer {


protected Class<?>[] getRootConfigClasses() {
    return new Class[] {SecSecurityConfig.class};
}}

this means you create the following class which will be instanciated autoatically

SecSecurityConfig.class : is the class where you do all http.csrf().disable().authorizeRequests()... configurations

source : https://www.baeldung.com/spring-security-login

hope it helps :)

Is there a way to maintain query params from the initial request , I have this route: router.get('/auth', passport.authenticate('oauth2')); When I GitHub is home to over 50 million developers working together to and pass in the redirectUri with query parameters in the passport.authenticate() call, app. get( `/auth/callback`, passport.authenticate('google', { failureRedirect:� During a user's authentication, the redirect_uri request parameter is used as a callback URL. This is where your application receives and processes the response from Auth0, and is often the URL to which users are redirected once the authentication is complete. To learn more about how the redirect_uri works, see OAuth 2.0 Authorization Framework.

Params, Choose a section, open( filePath, [mode] ), check( val, sets, [tags] ) � fail( [err] ) � group( name, Params.auth, string, The authentication method used for the request. It currently Params.redirects, number, The number of redirects to follow for this request. discardResponseBodies is set to false or not set at all. Try reproducing the issue during which you capture a Fiddler trace on the authentication request sent by the application to AD FS. Examine the request parameters to do the following checks depending on the request type. OAuth requests. An OAuth request looks like the following:

Action Controller Overview — Ruby on Rails Guides, How to use Action Controller's built-in HTTP authentication. Parameters Filtering; Redirects Filtering Rails does not make any distinction between query string parameters and POST parameters, and both are available in the params hash It is not meant as a silver bullet to handle all of your parameter filtering problems. AADSTS901002: The 'resource' request parameter is not supported. AADSTS90101: InvalidEmailAddress - The supplied data isn't a valid email address. The email address must be in the format someone@example.com. AADSTS90102: InvalidUriParameter - The value must be a valid absolute URI. AADSTS90107: InvalidXml - The request is not valid.

CAS - CAS Protocol Specification, The following HTTP request parameters may be passed to /login while it is acting as a If a service is not specified and a single sign-on session already exists, CAS CAS MUST redirect the client to this URL upon successful authentication. CAS MUST respond with a ticket validation failure response when a proxy ticket� Redirect URI (reply URL) restrictions and limitations. 08/07/2020; 5 minutes to read +2; In this article. A redirect URI, or reply URL, is the location where the authorization server sends the user once the app has been successfully authorized and granted an authorization code or access token.

Comments
  • How do you get the param? Could you please track the network to find whether the url is requested with error=fail?