Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

redirect - Redirection to originally requested page after successful login is not working in spring boot web mvc

I am trying to build web application which uses spring security form login for authentication. Basically, I am trying to build following workflow:

index.html is home page of the application, which is accessible to all users and it contains link to a protected page submitarticle.html, which is placed inside a folder author. When user clicks on the link, it is redirected to loginregister.html page for login process. And, after successful login and the logged in user has role "ROLE_AUTHOR", it redirects to the originally requested page "submitarticle.html". However, it is redirecting to index page. I have used http header to get the originally requested url as request.getHeader("Referer"). But, when I am on the index page and click on the protected page submitarticle.html, "referer" page seems to be index page itself. So, after successful login, it is redirected to index page. Please help me identify what I may be missing here.

WebSecurityConfig.java

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true)

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {   
    
    @Bean
    public AuthenticationSuccessHandler successHandler() {
        return new CustomSuccessHandler("/");
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception { 
        http.authorizeRequests().antMatchers("/", "/login", "/logout", "/register").permitAll();
         
     // submitarticle.html should be accessible to user with role Author only.
        http.authorizeRequests().antMatchers("/author/**").access("hasRole('ROLE_AUTHOR')");
         // Config for Login Form
        http.authorizeRequests().and().formLogin()//
                // Submit URL of login page.
                .loginProcessingUrl("/loginregister") // Submit URL                
                .loginPage("/loginregister")//
                .successHandler(successHandler())//
                .failureUrl("/loginregister?error=true")//
                .usernameParameter("username")//
                .passwordParameter("password")
                // Config for Logout Page
                .and().logout().logoutUrl("/logout").logoutSuccessUrl("/");    
 }

CustomSuccessHandler.java

public CustomSuccessHandler(String defaultTargetUrl) {          
            
            setDefaultTargetUrl(defaultTargetUrl);
            setUseReferer(true);
        }
     @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException 
    { 
            Object redirectURLObject = request.getSession().getAttribute("original_url");      
            String url = null;
           if(redirectURLObject != null)
           {
             url = redirectURLObject.toString();          
             getRedirectStrategy().sendRedirect(request, response, url); 
             request.getSession().removeAttribute("original_url");
           }
           // If request url is null then redirect to home page "/"
           else
           {
             getRedirectStrategy().sendRedirect(request, response, "/");
           }            
        }

Controller

@RequestMapping(value = "/loginregister", method = RequestMethod.GET)
    public String loginRegisterPage(AuthorRegistrationForm authorRegistrationForm, Model model, HttpServletRequest request) {
        
        String referer = request.getHeader("Referer");
        //save referer URL to session, for later use on CustomAuthenticationSuccesshandler
        request.getSession().setAttribute("original_url", referer);
        
        return "loginregister";
    }

loginregister.html

<form class="sj-formtheme sj-formlogin" action="/loginregister" method="post">
                                                <fieldset>
                                                    <div class="form-group">
                                                        <input type="text" name="username" class="form-control" placeholder="Username*" required="">
                                                    </div>
                                                    <div class="form-group">
                                                        <input type="password" name="password" class="form-control" placeholder="Password*" required="">
                                                    </div>
                                                    
                                                    <div class="sj-btnarea">
                                                        <button name="login-submit" class="sj-btn sj-btnactive">Login</button>
                                                    </div>
                                                </fieldset>
                                            </form>
question from:https://stackoverflow.com/questions/65938282/redirection-to-originally-requested-page-after-successful-login-is-not-working-i

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found the solution to my problem in Redirect to protected page after authentication

In CustomSuccessHandler class, I used DefaultSavedRequest object to get the original request object as below:

DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST");
        if(defaultSavedRequest != null)
           url = defaultSavedRequest.getRedirectUrl();

and I used that url for redirection.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...