我正在尝试对基于Spring Framework 2.5的应用程序实现Facebook登录,该应用程序已经具有常规的登录/密码身份验证.
我在控制器中找到了这部分代码,在userFb对象中有用户的Facebook数据:
String code = request.getParameter("code");
String accessToken = fbStuffKeeper.retrieveAccessToken(code);
facebookClient = new DefaultFacebookClient(accessToken);
User userFb = facebookClient.fetchObject("me", User.class);
我可以检查用户是否已经在数据库中,如果不能,我可以将其存储在数据库中,并存储其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用户?另一个身份验证提供者?有什么办法可以使用与我提到的类似的代码进行登录?
非常感谢你.
***编辑:
非常感谢你.看起来可能有所帮助.我现在有一个要登录的数据库用户.我在控制器中编写了以下代码:
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 */
现在一切正常.再次感谢您的帮助.
解决方法:
一种可能的方法如下.尽管它可能并不完美,但是效果很好.
创建一个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