Search code examples
spring-bootspring-securityurl-routing

Spring Boot Redirect to requested URL after login


I have a Spring Boot UI application. I am trying to redirect users to the originally requested URL after login.

When a user requests http://www.example.com/myapp/user/22, the application aptly redirects to http://www.example.com/myapp/login. Once the user logs in, the application redirects to http://www.example.com/myapp/dashboard. I would like the application to redirect to http://www.example.com/myapp/user/22.

I have gone through several links and feel I have a proper configuration, yet, redirection is not working as expected.

My Security Config is

public class SecurityConfig extends WebSecurityConfigurerAdapter {
.....
....

    @Autowired
    private MyAuthenticationSuccessHandler authenticationSuccessHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
        authorizeRequests()
                .antMatchers("/user/**").authenticated()
                .and().csrf().disable().formLogin()
                .successHandler(authenticationSuccessHandler)
......

and My Success Handler is

    @Component
    public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    ...
public MyAuthenticationSuccessHandler() {
        super();
        this.setDefaultTargetUrl("/myapp/dashboard");
        this.setUseReferer(true);
    }

        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                Authentication authentication) throws IOException, ServletException {
            //Do something ..........
            ........
            .........
            super.onAuthenticationSuccess(request, response, authentication);
}

I tried using SavedRequestAwareAuthenticationSuccessHandler too.

I notice that my success handler is invoked, but the target URL is always /user/login and my login controller is invoked..

@RequestMapping("/login")
public ModelAndView login(@ModelAttribute() {
    if(!userIdentified) {
        //go to login page
    } else {
        new ModelAndView("redirect:/myapp/dashboard");
    }
}

and the user is redirected to "dashboard".

What else am I missing?


Solution

  • Use "Referer" from session attribute to get the latest request URL. On my app, i use this one

    public class CustomAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    
        public static final String REDIRECT_URL_SESSION_ATTRIBUTE_NAME = "REDIRECT_URL";
    
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                Authentication authentication) throws IOException, ServletException {
    
            Object redirectURLObject = request.getSession().getAttribute(REDIRECT_URL_SESSION_ATTRIBUTE_NAME);
    
            if(redirectURLObject != null)
                setDefaultTargetUrl(redirectURLObject.toString());
            else{
                setDefaultTargetUrl("/");
            }
    
            request.getSession().removeAttribute(REDIRECT_URL_SESSION_ATTRIBUTE_NAME);
            super.onAuthenticationSuccess(request, response, authentication);
        }
    
    }
    

    Edit :

    Sorry i forgot to show the login controller

    @RequestMapping(method = RequestMethod.GET, value = {"/login"})
        String login(Model model, Principal principal, HttpServletRequest request) throws Exception{
            String referer = request.getHeader("Referer"); //Get previous URL before call '/login'
    
            //save referer URL to session, for later use on CustomAuthenticationSuccesshandler
            request.getSession().setAttribute(CustomAuthenticationSuccessHandler.REDIRECT_URL_SESSION_ATTRIBUTE_NAME, referer); 
    
    
            return principal == null ?  "login" : "redirect:/"; 
        }