2

我使用 sql-db 上的用户名/密码组合作为凭据,通过 spring-security 保护了一个小 webapp。

我现在想用 spring-social 添加 facebook/twitter 身份验证。使用这些示例,我可以将用户凭据存储在我的数据库中。我现在正在使用以下代码对用户在我的应用程序上的当前会话进行身份验证:

public String signIn(String userId, Connection<?> connection, NativeWebRequest request) {

    User user = userService.getUserById(Long.parseLong(userId));
    user.setPassword(this.passwordEncoder.encodePassword(user.getAccessToken(), this.salt));
    this.userService.store(user);

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getDisplayName(), user.getAccessToken());

    HttpServletRequest req = request.getNativeRequest(HttpServletRequest.class); // generate session if one doesn't exist
    token.setDetails(new WebAuthenticationDetails(req));
    Authentication authenticatedUser = this.authenticationManager.authenticate(token);
    SecurityContextHolder.getContext().setAuthentication(authenticatedUser);

    return "/user/dashboard";
}

身份验证有效,我没有收到任何 BadCredential 异常。但是在被重定向到 /user/dashboard 后,我又回到了登录状态。

我没有想法,在经典注册后,用于验证会话的类似代码正在运行。

有谁知道为什么会发生这种情况或如何调试它?

首先十分感谢!亨德里克

4

1 回答 1

1

我有类似的代码对我有用,并且还添加了“记住我”支持:

// lookup by id, which in my case is the login
User user = userService.findByLogin(userId);
// code to populate the user's roles
List<GrantedAuthority> authorities = ...;
// create new instance of my UserDetails implementation
UserDetailsImpl springSecurityUser = new UserDetailsImpl(user, authorities);
// create new Authentication using UserDetails instance, password, and roles
Authentication authentication = new UsernamePasswordAuthenticationToken(springSecurityUser, user.getPassword(), authorities);
// set the Authentication in the SecurityContext
SecurityContextHolder.getContext().setAuthentication(authentication);
// optional: remember-me support (must @Autowire in TokenBasedRememberMeServices)
tokenBasedRememberMeServices.onLoginSuccess(
    (HttpServletRequest) request.getNativeRequest(),
    (HttpServletResponse) request.getNativeResponse(),
    authentication);
于 2012-03-22T06:31:42.117 回答