编程语言
首页 > 编程语言> > java – 没有Spring安全性记住我以编程方式登录时创建的cookie

java – 没有Spring安全性记住我以编程方式登录时创建的cookie

作者:互联网

注册(注册)后,我通过Spring Security以编程方式登录我的用户:

public register(HttpServletRequest request, String user, String password) {
    ...
    request.login(user, password);
}

这工作正常,但它不会创建记住我的cookie(尽管使用交互式登录可以很好地创建cookie).
现在我已经阅读了thisthis的答案,你必须连接到RememberMeServices的实现(我使用PersistentTokenBasedRememberMeServices),然后调用onLoginSuccess.我没有成功自动装配PersistentTokenBasedRememberMeServices.
如何使这项工作?这是正确的方法吗?为什么Spring Security不提供更方便的方式?

P.S.:这是我的配置的摘录:

@Configuration
@EnableWebSecurity
public class WebSecConf extends WebSecurityConfigurerAdapter {

    ...

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

        http
            .rememberMe()
                .tokenRepository(new MyPersistentTokenRepository())
                .rememberMeCookieName("rememberme")
                .tokenValiditySeconds(60 * 60 * 24) 
                .alwaysRemember(true)
                .useSecureCookie(true)
                .and()
            ....
       ...
    }
}

解决方法:

你没有提到Spring版本.以下配置适用于Spring 4,但您可以将其修改为其他版本.在您的WebSecConf类autowire PersistentTokenRepository和UserDetailsS​​ervice接口中.添加Bean以获取PersistentTokenBasedRememberMeServices实例.

@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;
  }
}

现在,在您正在进行程序化登录的Controller或类中,自动装配PersistentTokenBasedRememberMeServices并在方法内添加以下代码以调用loginSuccess方法.

@Autowired
PersistentTokenBasedRememberMeServices persistentTokenBasedRememberMeServices;

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

标签:java,spring,spring-security,spring-social
来源: https://codeday.me/bug/20190608/1198281.html