Реализация авторизации токена OAuth2 и поддержка нескольких социальных сервисов. OAuth2ResourceServerConfiguration требуется один компонент - PullRequest
0 голосов
/ 13 марта 2019

Я реализую приложение с загрузочной пружиной, которое должно обеспечивать авторизацию токена OAuth2 и поддерживать несколько социальных служб. Я реализую этот подход, используя https://spring.io/guides/tutorials/spring-boot-oauth2/#_social_login_manual.

а также

http://www.littlebigextra.com/spring-boot-oauth2-tutorial-for-authorizing-through-facebook-google-linkedin-and-twitter/

Проблема, которую я получаю,

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerConfiguration required a single bean, but 3 were found:
    - facebookResource: defined by method 'facebookResource' in class path resource [com/sawian/config/SecurityConfiguration.class]
    - googleResource: defined by method 'googleResource' in class path resource [com/sawian/config/SecurityConfiguration.class]
    - resourceServerProperties: defined by method 'resourceServerProperties' in class path resource [org/springframework/boot/autoconfigure/security/oauth2/OAuth2AutoConfiguration.class]


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

My Security Config class

SecutityConfiguration.java

@Configuration
@EnableWebMvc
@EnableOAuth2Client
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Import(SecurityProblemSupport.class)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Resource
    private UserDetailsService userDetailsService;

    @Autowired
    OAuth2ClientContext oauth2ClientContext;

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

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
            .passwordEncoder(encoder());
    }



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            .and()
                .anonymous().disable()
                .headers().frameOptions().sameOrigin()
            .and()
                .authorizeRequests()
                .antMatchers("/", "/connect**", "/webjars/**").permitAll()
                .antMatchers("/api-docs/**").permitAll()
                .antMatchers("/api/**").authenticated()
                .antMatchers(HttpMethod.POST, "/api/users").permitAll()
            .and()
                .logout()
                .logoutSuccessUrl("/").permitAll()
                .logoutUrl("/api/logout").permitAll()
            .and()
            .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
    }

    private Filter ssoFilter() {

        CompositeFilter filter = new CompositeFilter();
        List<Filter> filters = new ArrayList<>();

        OAuth2ClientAuthenticationProcessingFilter facebookFilter = new OAuth2ClientAuthenticationProcessingFilter(
            "/connect/facebook");
        OAuth2RestTemplate facebookTemplate = new OAuth2RestTemplate(facebook(), oauth2ClientContext);
        facebookFilter.setRestTemplate(facebookTemplate);
        UserInfoTokenServices tokenServices = new UserInfoTokenServices(facebookResource().getUserInfoUri(),
            facebook().getClientId());
        tokenServices.setRestTemplate(facebookTemplate);
        facebookFilter.setTokenServices(tokenServices);

        OAuth2ClientAuthenticationProcessingFilter googleFilter = new OAuth2ClientAuthenticationProcessingFilter(
            "/connect/google");
        OAuth2RestTemplate googleTemplate = new OAuth2RestTemplate(google(), oauth2ClientContext);
        googleFilter.setRestTemplate(googleTemplate);
        tokenServices = new UserInfoTokenServices(googleResource().getUserInfoUri(), google().getClientId());
        tokenServices.setRestTemplate(googleTemplate);
        googleFilter.setTokenServices(tokenServices);

        filters.add(facebookFilter);
        filters.add(googleFilter);
        filter.setFilters(filters);

        return filter;
    }

    @Bean
    @ConfigurationProperties("facebook.client")
    public AuthorizationCodeResourceDetails facebook() {
        return new AuthorizationCodeResourceDetails();
    }

    @Bean
    @ConfigurationProperties("facebook.resource")
    public ResourceServerProperties facebookResource() {
        return new ResourceServerProperties();
    }

    @Bean
    @ConfigurationProperties("google.client")
    public AuthorizationCodeResourceDetails google() {
        return new AuthorizationCodeResourceDetails();
    }

    @Bean
    @ConfigurationProperties("google.resource")
    public ResourceServerProperties googleResource() {
        return new ResourceServerProperties();
    }




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

Может кто-нибудь помочь, где может быть проблема.

...