Spring Social facebook + Spring Security

cha*_*ean 6 spring facebook 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>
Run Code Online (Sandbox Code Playgroud)

所以,据我所知,这种方法发挥作用:

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

userId从" #{request.userPrincipal.name}."中复活.所以,我的问题是:userId如果我想获得这个" userId" ,我怎么能把" " 传递给这个方法SecurityContextHolder.getContext().getAuthentication().getPrincipal().

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

Mak*_*das 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();
    }

}
Run Code Online (Sandbox Code Playgroud)

你也可以在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>
Run Code Online (Sandbox Code Playgroud)