Spring Security 2.0 Facebook Connect

时间:2011-04-12 14:17:47

标签: spring spring-mvc facebook spring-security

我正在尝试将Facebook登录到我们基于Spring Framework 2.5的应用程序,该应用程序已经具有通常的登录/密码身份验证。

我在我的控制器中找到了这部分代码,我在userFb对象中有用户的Facebook数据:

String code = request.getParameter("code");
String accessToken = fbStuffKeeper.retrieveAccessToken(code);
facebookClient = new DefaultFacebookClient(accessToken);
User userFb = facebookClient.fetchObject("me", User.class);

我可以检查用户是否已经在DB中,如果不是,我可以将他存储在数据库中并存储他的FB_uid和其他必要的凭据。 问题是我想在某些情况下登录此用户,如果他已经获得系统授权。 我当前的身份验证管理器根据此规则决定:

<authentication-provider>
    <jdbc-user-service data-source-ref="dataSource"
                       users-by-username-query="select username, password, confirmed, 1 AS enabled FROM person WHERE confirmed=1 and username=?"
                       authorities-by-username-query="select username, authority from person where username=?"/>
    <password-encoder hash="md5"/>
</authentication-provider>

所以我的问题是:如何登录尝试使用Facebook连接的DB中找到的用户?另一个认证提供商有没有办法使用我提到的类似代码进行登录?

非常感谢你。

* * *编辑: 非常感谢你。它看起来可能有所帮助。我现在在DB中有一个用户,我想登录。我在控制器中创建了这段代码:

User userFb = facebookClient.fetchObject("me", User.class);
Person person = personDao.getPersonByFbUid(userFb.getId());
GrantedAuthority[] grantedAuthorities = new GrantedAuthorityImpl[1];
grantedAuthorities[0] = new GrantedAuthorityImpl(person.getAuthority());
Authentication a = new FacebookAuthenticationToken(grantedAuthorities, person);
a.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(a);

我还创建了FacebookAuthenticationToken:

public class FacebookAuthenticationToken extends AbstractAuthenticationToken {
private Person person;
   public FacebookAuthenticationToken(GrantedAuthority[] authorities, Person person) {
    super(authorities);
    this.person = person;
}
public Object getCredentials() {
    return person;
}
public Object getPrincipal() {
    this.person;
} /* +  Person getter and setter */

现在一切正常。再次感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

一种可能的方式是遵循。虽然它可能不完美,但效果很好。

创建一个FacebookAuthenticationToken类,扩展AbstractAuthenticationToken并保存您的facebook用户对象(假设它为FacebookUser)。

在您上面提到的代码之后,将以下代码紧跟在同一个控制器中:

String code = request.getParameter("code");
String accessToken = fbStuffKeeper.retrieveAccessToken(code);
facebookClient = new DefaultFacebookClient(accessToken);
User userFb = facebookClient.fetchObject("me", User.class);

// Find FacebookUser with current FB_uid, create new if found none, load its information in an instance of FacebookUser

Authentication a = new FacebookAuthenticationToken(fbUserObject);
a.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(a);

// your authentication is complete, redirect to some other page