Summary

when i visit localhost/p,then redirect to login page. When login successfull, it just redirect to localhost/error, not localhost/p.

Actual Behavior

  1. I am visite localhost/p
  2. redirect to login page
  3. login success, redirect to localhost/error but i want to redirect to localhost/p when i login success

Configuration

`@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().mvcMatchers("/css/**");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/login").permitAll()
            .anyRequest().fullyAuthenticated()
            .and()
            .formLogin().loginPage("/login").failureUrl("/login?error")
            .and()
            .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .and()
            .exceptionHandling().accessDeniedPage("/access?error")
    .and().csrf().disable();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().passwordEncoder(NoOpPasswordEncoder.getInstance()).withUser(User.builder().username("admin").password("1").roles("ADMIN", "USER", "ACTUATOR"));
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

}`

Version

  1. SpringBoot 2.0.3.RELEASE 2.spring-security-oauth2 2.3.3.RELEASE 3.spring-security-oauth2-autoconfigure 2.0.1.RELEASE

Sample

https://github.com/45104799/boot-security-test

Comment From: mhyeon-lee

Implement AuthenticationSuccessHandler to set the path to redirect after login. You can use the Referer or queryParameter, or you can directly determine the redirect url.

public class RedirectAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    @Autowired
    public RedirectAuthenticationSuccessHandler(RedirectUriProvider redirectUriProvider) {
        setUseReferer(true);   // use referer
        //  setTargetUrlParameter(REDIRECT_PARAMETER);   // if you want to use query param
    }

       // determine target url if you want override
       //  @Override
    //protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response){
         // } 
}
http
    .formLogin()
        .loginProcessingUrl(LOGIN_PATH)
    .successHandler(new RedirectAuthenticationSuccessHandler());

Comment From: 45104799

I want to keep "pre login url" and when login success will redirect to this url.

Comment From: mhyeon-lee

@45104799 Yes, you need to implement determineTargetUrl in AuthenticationSuccessHandler. Any way

  • e.g.

pre login url: localhost/p login url : localhost/login?redirect=http://localhost/p // send pre login url anyway (queryparam, header.. )

public class RedirectAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
         @Override
    protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response){
            //   you should check if the redirect parameter is missing or not in url format.
            return (String) request.getParameter("redirect");
         } 
}

Any other problems? Or did I misunderstand the problem?

Comment From: 45104799

got it, thank you!

Comment From: 45104799

I didn't change any code, but this morning, she redirected to the correct url! I still want to thank you!

Comment From: sravantatikonda1893

Hi @mhyeon-lee ,

I debugged as you suggested my redirect parameter is coming as null. Screen Shot 2020-02-20 at 10 33 39 AM

Any idea what's causing it to be empty? I'm using Database based authentication, authentication of the user is successful, but the redirection is going to home page but not the secured URL(in my case, its a "Download file" button on the home page). I also tested by ".antMatchers("/download/**").authenticated()", making this permitAll, I was able to download, so its not an issue with the download as well.

My WebSecurityConfig class as below:

Configuration

@EnableWebSecurity
@Slf4j
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

  private final UserDetailsService userDetailsService;
  private final AuthenticationManagerBuilder authenticationManagerBuilder;

  public WebSecurityConfiguration(
      @Qualifier("userDetailsService") UserDetailsService userDetailsService,
      AuthenticationManagerBuilder authenticationManagerBuilder) {
    this.userDetailsService = userDetailsService;
    this.authenticationManagerBuilder = authenticationManagerBuilder;
  }

  @Override
  public void configure(HttpSecurity http) throws Exception {
    http
        .headers().frameOptions().disable()
        .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .csrf().disable()
        .authorizeRequests()
        //.antMatchers("/authenticate/**").permitAll()
        .antMatchers("/download/**").authenticated()
        //.antMatchers("/hello/**").authenticated()
        .antMatchers("/", "/home").permitAll()
        //.antMatchers("validate/**").permitAll()
        .anyRequest().authenticated()
        .antMatchers("/v2/api-docs",
            "/swagger-resources/**",
            "/swagger-ui.html",
            "/webjars/**"
        ).permitAll()
        .and()
        .formLogin()
        .loginPage("/login").permitAll()
        //  .successHandler(new RefererRedirectionAuthenticationSuccessHandler())
        .and()
        .logout()
        .permitAll();
  }

  /*@Bean
  public AuthenticationSuccessHandler successHandler() {
    return new MyCustomLoginSuccessHandler("/download/file/");
  }*/

  @PostConstruct
  public void init() {
    authenticationManagerBuilder.authenticationProvider(authenticationProvider());
  }

  public AuthenticationProvider authenticationProvider() {
    CustomDaoAuthenticationProvider provider = new CustomDaoAuthenticationProvider();
    provider.setUserDetailsService(userDetailsService);
    provider.setPasswordEncoder(passwordEncoder());
    return provider;
  }

  @Override
  @Bean
  public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
  }

  @Bean
  public BCryptPasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }
}

I tried debugging the default implementation of SavedRequestAwareAuthenticationSuccessHandler class, the saved request is returning null too. Am I missing something in the implementation? Screen Shot 2020-02-20 at 10 37 37 AM

Comment From: sravantatikonda1893

Quick update:

I was able to fix it by removing the following line from webSecurityConfiguration class

    .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)