Dmitrij Kostyushko
Dmitrij Kostyushko

Reputation: 656

Return to the previous page after authorization, Spring Security AuthenticationSuccessHundler

I have a login page (/page/login) and dropdown login forms in every page. I want user to be redirected to the page from which he has logged in (by dropdown login form), or the home page if it was from login page.

I tried to use AuthenticationSuccessHandler but it does not seems to work, every time it just redirects user to home page. What is the right way to solve it?

    @Component
    public class MySimpleUrlAuthenticationSuccessHendler implements AuthenticationSuccessHandler {

        @Override
        public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                            HttpServletResponse httpServletResponse,
                                            Authentication authentication) throws IOException {
            if(httpServletRequest.getContextPath().equals("/login")){
                sendRedirect(httpServletRequest, httpServletResponse, "/user/profile");
            }
            else{
                sendRedirect(httpServletRequest, httpServletResponse,httpServletRequest.getContextPath());
            }

        }
        private void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
            if(!response.isCommitted()){
                new DefaultRedirectStrategy().sendRedirect(request,response,url);
            }
        }
    }

Spring security config

package com.example.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

    @Configuration
    public class DemoSpringSecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired
        AuthenticationSuccessHandler authenticationSuccessHandler;
        @Autowired
        UserDetailsService userDetailsService;

        @Override
        protected void configure(HttpSecurity http) throws Exception {

            http.authorizeRequests()


                    .regexMatchers(HttpMethod.GET, "rating/place/[0-9]{0,}", "/place/[0-9]{0,}/liked/", "/rating/place/[0-9]{0,}")
                    .hasRole("USER")

                    .antMatchers(HttpMethod.GET, "/user/orders",
                            "/user/places")
                    .hasRole("USER")

                    .regexMatchers(HttpMethod.POST, "/menu/[0-9]{0,}/comment",
                            "/place/[0-9]{0,}/menu/[0-9]{0,}")
                    .hasRole("USER")

                    .regexMatchers(HttpMethod.POST, "/place/menu/[0-9]{0,}")
                    .hasRole("OWNER")

                    .antMatchers(HttpMethod.GET, "/newplace")
                    .authenticated()

                    .antMatchers(HttpMethod.POST, "/newplace")
                    .authenticated()

                    .antMatchers(HttpMethod.POST, "/registration")
                    .permitAll()

                    .antMatchers(HttpMethod.GET, "/resend", "/page/login", "/registration", "/place/")
                    .permitAll();

            http
                    .logout()
                    .logoutUrl("/logout")
                    .logoutSuccessUrl("/");

            http
                    .rememberMe()
                    .key("rememberme");

            http
                    .formLogin()
                    .loginPage("/page/login")
                    .failureUrl("/page/login")
                    .loginProcessingUrl("/login")
                    .usernameParameter("j_username")
                    .passwordParameter("j_password")

.successHandler(authenticationSuccessHandler);

            http.
                    userDetailsService(userDetailsService);


            http.
                    csrf().disable();

        }

    }

Upvotes: 1

Views: 2408

Answers (2)

Amit
Amit

Reputation: 13364

I also had similar requirement in my project and I solved this using below step:-

  1. When the login form in dropdown is submitted I also send the current url (window.location.href) as a hidden request parameter.

  2. Inside UserNamePasswordFilter and I get this parameter from request and store it in session (say variable name is redirectPrevUrl).

  3. Now, in authentication success handler if this variable is present (i.e. redirectPrevUrl!=null) I redirect to this url instead of default home page.

This worked for me and I hope it will work for you as well,

Upvotes: 2

dur
dur

Reputation: 16992

You need something like this in your AuthenticationSuccessHandler.

Upvotes: 3

Related Questions