Spring社交Facebook在版本2.0.2中不起作用

时间:2018-06-05 03:14:29

标签: spring-boot spring-social-facebook

大家好,当我将我的应用程序升级到spring 2.0.2时,我得到了这个例外:

  

描述:com.ssp.api.v1.security.SecurityConfiguration中的字段connectionFactoryLocator需要一个类型为' org.springframework.social.connect.ConnectionFactoryLocator'的bean。无法找到。

这是我的代码:

SecurityConfiguration.java配置

@Configuration
@ComponentScan(basePackages = { "com.ssp.api.vi.security" })
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired private ConnectionFactoryLocator connectionFactoryLocator;
    @Autowired private UsersConnectionRepository usersConnectionRepository;
    @Autowired private FacebookConnectionSignup facebookConnectionSignup;
    @Autowired private SspUserDetailsService sspUserDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/api/session").permitAll()
                .antMatchers("/h2-console/**").permitAll()
                .antMatchers("/api/**").authenticated()
                .and()
                .requestCache()
                .requestCache(new NullRequestCache())
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and().csrf().disable();
    }

    //@Autowired
    @Bean
    public ProviderSignInController providerSignInController() {
        ((InMemoryUsersConnectionRepository) usersConnectionRepository)
          .setConnectionSignUp(facebookConnectionSignup);

        return new ProviderSignInController(
          connectionFactoryLocator, 
          usersConnectionRepository, 
          new FacebookSignInAdapter());
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
      throws Exception {
        auth.authenticationProvider(authenticationProvider());
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider
          = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(sspUserDetailsService);
        authProvider.setPasswordEncoder(encoder());
        return authProvider;
    }

    @Bean
    public PasswordEncoder encoder() {
        return new BCryptPasswordEncoder(11);
    }

    @Override
    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); }

    @Override
    @Bean(name = BeanIds.USER_DETAILS_SERVICE)
    public UserDetailsService userDetailsServiceBean() throws Exception { return this.sspUserDetailsService; }

AuthUtil.java类

protected static final Logger log = LoggerFactory.getLogger(AuthUtil.class);

    public static void authenticate(Connection<?> connection) {
        UserProfile userProfile = connection.fetchUserProfile();
        String username = userProfile.getUsername();
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, null, null);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        log.info("User {} {} connected.", userProfile.getFirstName(), userProfile.getLastName());
    }

FacebookConnectionSignup.class服务

@Service
public class FacebookConnectionSignup implements ConnectionSignUp {

    @Override
    public String execute(Connection<?> connection) {

        return connection.getDisplayName();
    }
}

FacebookSignInAdapter.java类

public class FacebookSignInAdapter implements SignInAdapter{
    @Override
    public String signIn(String userId, Connection<?> connection, NativeWebRequest request) {

        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(
                connection.getDisplayName(), null, 
              Arrays.asList(new SimpleGrantedAuthority("FACEBOOK_USER"))
              )
        );

        return null;
    }
}

SocialConfiguration.java配置

 @Configuration
    public class SocialConfiguration {
        @Bean
        public SignInAdapter authSignInAdapter() {
            return (userId, connection, request) -> {
                AuthUtil.authenticate(connection);
                return null;
            };
        }
    }

### SspUserDetailsService.class Service

@Service
public class SspUserDetailsService implements UserDetailsService {
    @Autowired private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findById(username).orElse(null);
        if (user == null)
            throw new UsernameNotFoundException(username);

        return new SspUserDetails(user);
    }
}

控制台错误:

Description:

Field connectionFactoryLocator in com.ssp.api.v1.security.SecurityConfiguration required a bean of type 'org.springframework.social.connect.ConnectionFactoryLocator' that could not be found.


Action:

Consider defining a bean of type 'org.springframework.social.connect.ConnectionFactoryLocator' in your configuration.

此代码在Spring 1.5.10版本中完美运行。

我该如何解决这个问题?

在感谢之前!

1 个答案:

答案 0 :(得分:0)

在Boot 2.x中,您需要在ConnectionFactoryLocator类中定义UsersConnectionRepositorySecurityConfiguration,而不是自动装配它们:

private ConnectionFactoryLocator connectionFactoryLocator() {
    ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();
    registry.addConnectionFactory(new FacebookConnectionFactory(appId, appSecret));
    return registry;
}

private UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
    return new InMemoryUsersConnectionRepository(connectionFactoryLocator);
} 

在这里,appIdappSecret来自application.properties。

您还需要更改ProviderSignInController bean的实现:

@Bean
public ProviderSignInController providerSignInController() {
    ConnectionFactoryLocator connectionFactoryLocator = connectionFactoryLocator();
    UsersConnectionRepository usersConnectionRepository = getUsersConnectionRepository(connectionFactoryLocator);
    ((InMemoryUsersConnectionRepository) usersConnectionRepository).setConnectionSignUp(facebookConnectionSignup);
    return new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository, new FacebookSignInAdapter());
}

您可以找到更多详细信息here