Spring Social facebook + Spring Security

时间:2013-04-10 07:13:41

标签: facebook spring spring-security spring-social

我想将Spring Social facebook与Spring Security集成到我的应用程序中(我使用xml配置)。我需要的只是将Facebook帐户与我的应用程序的帐户连接。在简单的例子中,我发现了这个:

<bean id="connectionRepository" factory-method="createConnectionRepository" 
      factory-bean="usersConnectionRepository" scope="request">
    <constructor-arg value="#{request.userPrincipal.name}" />
    <aop:scoped-proxy proxy-target-class="false" />
</bean>

所以,据我所知,这种方法起作用了:

public ConnectionRepository createConnectionRepository(String userId) {
        if (userId == null) {
            throw new IllegalArgumentException("userId cannot be null");
        }
        return new JdbcConnectionRepository(userId, jdbcTemplate, connectionFactoryLocator, textEncryptor, tablePrefix);
    }

它从userId中重新获得“#{request.userPrincipal.name}”。那么,我的问题是:如何通过“userId” 如果我想使用userId获取此“SecurityContextHolder.getContext().getAuthentication().getPrincipal()”,请使用此方法。

我看到的唯一方法是创建JdbcUsersConnectionRepository的实现并重新定义createConnectionRepository(String userId)方法。但也许有更优雅的解决方案。

1 个答案:

答案 0 :(得分:7)

还有另一种方式:

<bean id="connectionRepository" factory-method="createConnectionRepository" factory-bean="usersConnectionRepository"
    scope="request">
    <constructor-arg value="#{authenticationService.getAuthenticatedUsername()}" />
    <aop:scoped-proxy proxy-target-class="false" />
</bean>

@Service("authenticationService")
public class AuthenticationService {

    public String getAuthenticatedUsername() {
        return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

}

你也可以在SPeL中完全做到(我不喜欢这种依赖):

<bean id="connectionRepository" factory-method="createConnectionRepository" factory-bean="usersConnectionRepository"
    scope="request">
    <constructor-arg value="#{T(org.springframework.security.core.context.SecurityContextHolder).getContext().getAuthentication().getPrincipal()}" />
    <aop:scoped-proxy proxy-target-class="false" />
</bean>