2012-02-15 111 views
2

我有一个由spring-security使用sql-db上的用户名/密码组合作为凭据的安全小webapp。如何将spring-social认证与spring-security结合起来?

我现在想用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后,我被抛回到登录页面。

我不知道,用于验证会话的类似代码片段在经典注册后工作。

有没有人有任何想法,为什么会发生这种情况或如何调试?

非常感谢! 亨德里克

+0

这一切都依赖。我遇到了同样的情况,事实证明,我的映射只允许角色“ROLE_ANONYMOUS”,我在登录后被拒绝访问。我必须更改它以允许“ROLE_USER”。出于某种原因,当直接使用spring security进行登录时(例如,基本或表单登录),这不是问题。 – 2013-01-03 19:59:53

回答

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); 
相关问题