No Spring Security Remember me cookie created when logging in programmatically

前端 未结 1 596
鱼传尺愫
鱼传尺愫 2021-01-13 11:32

Right after registration (sign up) I\'m logging in my user programmatically via Spring Security:

public register(HttpServletRequest request, String user, Str         


        
1条回答
  •  野的像风
    2021-01-13 12:11

    You didn't mention the Spring version. Below configuration will work with Spring 4 but you can modify it for other version. In your WebSecConf class autowire PersistentTokenRepository and UserDetailsService interfaces. Add Bean to get PersistentTokenBasedRememberMeServices instance.

    @Configuration
    @EnableWebSecurity
    public class WebSecConf extends WebSecurityConfigurerAdapter {
    
    @Autowired
    PersistentTokenRepository persistenceTokenRepository;
    @Autowired
    UserDetailsService userDetailsService;
        ...
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
    
            http
                .rememberMe()
                    .tokenRepository(persistenceTokenRepository)
                    .rememberMeCookieName("rememberme")
                    .tokenValiditySeconds(60 * 60 * 24) 
                    .alwaysRemember(true)
                    .useSecureCookie(true)
                    .and()
                ....
           ...
        }
    
    @Bean
    public PersistentTokenBasedRememberMeServices getPersistentTokenBasedRememberMeServices() {
        PersistentTokenBasedRememberMeServices persistenceTokenBasedservice = new PersistentTokenBasedRememberMeServices("rememberme", userDetailsService, persistenceTokenRepository);
        persistenceTokenBasedservice.setAlwaysRemember(true);
        return persistenceTokenBasedservice;
      }
    }
    

    Now in your Controller or class where you are doing programmatic login, autowire PersistentTokenBasedRememberMeServices and add below code inside the method to invoke loginSuccess method.

    @Autowired
    PersistentTokenBasedRememberMeServices persistentTokenBasedRememberMeServices;
    
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null){
            persistentTokenBasedRememberMeServices.loginSuccess(request, response, auth);
        }
    

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