6

我想使用 Spring Security 将 Spring Social facebook 集成到我的应用程序中(我使用 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)方法。但也许有更优雅的解决方案。

4

1 回答 1

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>
于 2013-04-10T12:06:50.410 回答