2012-02-15 117 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); 
相關問題