使用spring security进行手动身份验证并记住我的提供者

时间:2014-07-14 14:58:18

标签: java spring spring-mvc spring-security

我需要实现手动登录过程。身份验证工作正常:

UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword());
token.setDetails(new WebAuthenticationDetails(request));
Authentication authenticatedUser = authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authenticatedUser);

但是在这种情况下如何使用记住我的提供者呢? 提前谢谢

2 个答案:

答案 0 :(得分:4)

解决方案如下:

  1. 检查用户的密码
  2. 授权用户:

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword());
    token.setDetails(new WebAuthenticationDetails(request));                        
    Authentication authenticatedUser = authenticationManager.authenticate(token);
    SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
    
  3. 自动装配rememberMeService并致电:

  4. rememberMeServices.onLoginSuccess(request, response, authenticatedUser);

答案 1 :(得分:1)

很好的答案。它对我有用。

使用新版本的spring security:

RememberMeAuthenticationToken auth = new RememberMeAuthenticationToken("your key",userDetails,  autorities);
            String  p = request.getParameter("rememberme");
    //      your request need this parameter

            Authentication authenticatedUser = authenticationManager.authenticate(auth);
            SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
            myrememberMeService.loginSuccess(request, response, authenticatedUser);