Spring MVC and login redirect

前端 未结 2 826
梦毁少年i
梦毁少年i 2020-12-30 18:15

I have a web application, when a use click on a personal profile link, if he is not logged in, I would like to redirect him to login page, then when he logs in, I would to s

相关标签:
2条回答
  • 2020-12-30 18:45

    Fortunately, Spring Security has built-in functionality for remembering the URL that was originally requested, and redirecting your users there after they successfully login. The quick answer to your question is that you need to enable this functionality by setting the always-use-default-target option to false in your Spring Security configuration.

    For example, here's a common line from the Spring Security config:

    <form-login 
        login-page="/login.html"
        authentication-failure-url="/login.html?status=LOGIN_FAILURE"
        default-target-url="/secure/index.html"
        always-use-default-target="false" />
    

    This configuration will make the following two flows possible:

    Flow #1

    1. Sally requests /login.html
    2. Sally provides a valid username and password
    3. Sally is redirected to /secure/index.html, since that is the default-target-url

    Flow #2 (The flow you want)

    1. David requests /secure/kittens.html
    2. Since David is not logged-in, he is presented with the login page.
    3. After providing a valid username and password, David is redirected to /secure/kittens.html, which is the original page he was trying to access. (He is not taken to the default-target-url because always-use-default-target is set to false.)
    0 讨论(0)
  • 2020-12-30 18:49

    For those of you using Spring's JavaConfig, the same thing can be achieved using

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    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.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.crypto.password.PasswordEncoder;
    import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
    
    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        ...
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
             // authentication logic        
        }
    
        @Bean
        public PasswordEncoder passwordEncoder() {
            //password encoding logic
            //preferably BCrpyt
        }
    
        @Override
        public void configure(WebSecurity web) throws Exception {
             // @formatter:off
             web.ignoring()
               .antMatchers("/css/**")     //Allow CSS resources.
               .antMatchers("/js/**")      //Allow JavaScript resources.
               .antMatchers("/images/**"); //Allow image resources.
             // @formatter:on
        }        
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .formLogin()
                .loginPage("/login.html")                       //login-page
                .failureUrl("/login.html?status=LOGIN_FAILURE") //authentication-failure-url
                .defaultSuccessUrl("/secure/index.html", false) //default-target-url. set always-use-default-target to `false`
                .permitAll()
            .and()
                .logout()
                .permitAll()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
        }
    }
    

    The code snippet above shows a configuration without XML.

    1. The class is annotated with @Configuration indicating that

    a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime

    1. The class is annotated with @EnableWebSecurity which adds

    this annotation to an @Configuration class to have the Spring Security configuration defined in any WebSecurityConfigurer

    1. This class also extends WebSecurityConfigurerAdapter which

    Provides a convenient base class for creating a WebSecurityConfigurer instance. The implementation allows customization by overriding methods.

    1. You can Autowire an AuthenticationManagerBuilder in a public method to handle your authentication needs

    I hope this helps for those of you with a similar problem who don't use an XML configuration.

    0 讨论(0)
提交回复
热议问题