Bean of type 'org.springframework.security.oauth2.client.registration.ClientRegistrationRepository' that could not be found. – Spring Security

huangapple go评论91阅读模式
英文:

Bean of type 'org.springframework.security.oauth2.client.registration.ClientRegistrationRepository' that could not be found. - Spring Security

问题

我正在开发一个使用Spring Security和Google登录的Spring应用程序,但在执行应用程序时遇到以下错误:

***************************
应用启动失败
***************************

描述:

org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration中的springSecurityFilterChain方法需要一种类型为'org.springframework.security.oauth2.client.registration.ClientRegistrationRepository'的bean,但找不到该bean。

找到了以下候选项,但无法注入:
	- 由于未提供已注册的客户端,因此未加载'OAuth2ClientRegistrationRepositoryConfiguration'中的'clientRegistrationRepository' bean方法

操作:

请考虑重新查看上述条目或在配置中定义一种类型为'org.springframework.security.oauth2.client.registration.ClientRegistrationRepository'的bean。

我的application.yml配置文件:

spring:
    datasource:
        url: jdbc:mysql://localhost:3306/manager
        username: application_spring
        password: application_spring

    jpa:
        show-sql: true
        hibernate:
            ddl-auto: update
security:
      oauth2:
        client:
          registration:
            google:
              client-id: {客户端ID}
              client-secret: {客户端秘钥}
              redirectUri: "{baseUrl}/oauth2/callback/{registrationId}"
              scope:
                - email
                - profile
app:
  auth:
    tokenSecret: 926D96C90030DD58429D2751AC1BDBBC
    tokenExpirationMsec: 864000000
  oauth2:
    # 在与OAuth2提供者成功验证后,我们将为用户生成身份验证令牌,并将令牌发送到前端客户端在/oauth2/authorize请求中提到的redirectUri。
    # 我们不使用cookie,因为它们在移动客户端中效果不佳。
    authorizedRedirectUris:
      - http://localhost:3000/oauth2/redirect
      - myandroidapp://oauth2/redirect
      - myiosapp://oauth2/redirect

我的SecurityConfig类:

package com.manager.manager.config;

// ...(省略其他导入)

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        securedEnabled = true,
        jsr250Enabled = true,
        prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	// ...(省略其他成员变量和方法)
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                    .and()
                .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                .csrf()
                    .disable()
                .formLogin()
                    .disable()
                .httpBasic()
                    .disable()
                .exceptionHandling()
                    .authenticationEntryPoint(new RestAuthenticationEntryPoint())
                    .and()
                .authorizeRequests()
                    .antMatchers("/", "/error", "/favicon.ico", "/**/*.png", "/**/*.gif", "/**/*.svg", "/**/*.jpg", "/**/*.html", "/**/*.css", "/**/*.js")
                        .permitAll()
                    .antMatchers("/auth/**", "/oauth2/**")
                        .permitAll()
                    .anyRequest()
                        .authenticated()
                    .and()
                .oauth2Login()
                    .authorizationEndpoint()
                        .baseUri("/oauth2/authorize")
                        .authorizationRequestRepository(cookieAuthorizationRequestRepository())
                        .and()
                    .redirectionEndpoint()
                        .baseUri("/oauth2/callback/*")
                        .and()
                    .userInfoEndpoint()
                        .userService(customOAuth2UserService)
                        .and()
                    .successHandler(oAuth2AuthenticationSuccessHandler)
                    .failureHandler(oAuth2AuthenticationFailureHandler);

        // 向过滤器链中添加自定义的基于Token的身份验证过滤器
        http.addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}

我正在遵循这个教程完成应用程序:
https://www.callicoder.com/spring-boot-security-oauth2-social-login-part-2/

有人知道可能出现什么问题吗?
谢谢。

英文:

I am developing a spring application with spring-security and login with google but I get this error when executing the application:

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

Description:

Method springSecurityFilterChain in org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration required a bean of type 'org.springframework.security.oauth2.client.registration.ClientRegistrationRepository' that could not be found.

The following candidates were found but could not be injected:
	- Bean method 'clientRegistrationRepository' in 'OAuth2ClientRegistrationRepositoryConfiguration' not loaded because OAuth2 Clients Configured Condition registered clients is not available


Action:

Consider revisiting the entries above or defining a bean of type 'org.springframework.security.oauth2.client.registration.ClientRegistrationRepository' in your configuration.

My application.yml:

spring:
    datasource:
        url: jdbc:mysql://localhost:3306/manager
        username: application_spring
        password: application_spring

    jpa:
        show-sql: true
        hibernate:
            ddl-auto: update
security:
      oauth2:
        client:
          registration:
            google:
              client-id: {client id}
              client-secret: {client-secret}
              redirectUri: "{baseUrl}/oauth2/callback/{registrationId}"
              scope:
                - email
                - profile
app:
  auth:
    tokenSecret: 926D96C90030DD58429D2751AC1BDBBC
    tokenExpirationMsec: 864000000
  oauth2:
    # After successfully authenticating with the OAuth2 Provider,
    # we'll be generating an auth token for the user and sending the token to the
    # redirectUri mentioned by the frontend client in the /oauth2/authorize request.
    # We're not using cookies because they won't work well in mobile clients.
    authorizedRedirectUris:
      - http://localhost:3000/oauth2/redirect
      - myandroidapp://oauth2/redirect
      - myiosapp://oauth2/redirect

And my SecurityConfig class:

package com.manager.manager.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.manager.manager.security.oatuh2.CustomOAuth2UserService;
import com.manager.manager.security.oatuh2.HttpCookieOAuth2AuthorizationRequestRepository;
import com.manager.manager.security.oatuh2.OAuth2AuthenticationFailureHandler;
import com.manager.manager.security.oatuh2.OAuth2AuthenticationSuccessHandler;
import com.manager.manager.security.utils.RestAuthenticationEntryPoint;
import com.manager.manager.security.utils.TokenAuthenticationFilter;
import com.manager.manager.service.impl.CustomUserDetailsService;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        securedEnabled = true,
        jsr250Enabled = true,
        prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	@Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Autowired
    private CustomOAuth2UserService customOAuth2UserService;

    @Autowired
    private OAuth2AuthenticationSuccessHandler oAuth2AuthenticationSuccessHandler;

    @Autowired
    private OAuth2AuthenticationFailureHandler oAuth2AuthenticationFailureHandler;
    
    @Autowired
    private HttpCookieOAuth2AuthorizationRequestRepository httpCookieOAuth2AuthorizationRequestRepository;

    @Bean
    public TokenAuthenticationFilter tokenAuthenticationFilter() {
        return new TokenAuthenticationFilter();
    }

    /*
      By default, Spring OAuth2 uses HttpSessionOAuth2AuthorizationRequestRepository to save
      the authorization request. But, since our service is stateless, we can't save it in
      the session. We'll save the request in a Base64 encoded cookie instead.
    */
    @Bean
    public HttpCookieOAuth2AuthorizationRequestRepository cookieAuthorizationRequestRepository() {
        return new HttpCookieOAuth2AuthorizationRequestRepository();
    }
    
    @Override
    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder
                .userDetailsService(customUserDetailsService)
                .passwordEncoder(passwordEncoder());
    }

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

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                    .and()
                .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                .csrf()
                    .disable()
                .formLogin()
                    .disable()
                .httpBasic()
                    .disable()
                .exceptionHandling()
                    .authenticationEntryPoint(new RestAuthenticationEntryPoint())
                    .and()
                .authorizeRequests()
                    .antMatchers("/",
                        "/error",
                        "/favicon.ico",
                        "/**/*.png",
                        "/**/*.gif",
                        "/**/*.svg",
                        "/**/*.jpg",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js")
                        .permitAll()
                    .antMatchers("/auth/**", "/oauth2/**")
                        .permitAll()
                    .anyRequest()
                        .authenticated()
                    .and()
                .oauth2Login()
                    .authorizationEndpoint()
                        .baseUri("/oauth2/authorize")
                        .authorizationRequestRepository(cookieAuthorizationRequestRepository())
                        .and()
                    .redirectionEndpoint()
                        .baseUri("/oauth2/callback/*")
                        .and()
                    .userInfoEndpoint()
                        .userService(customOAuth2UserService)
                        .and()
                    .successHandler(oAuth2AuthenticationSuccessHandler)
                    .failureHandler(oAuth2AuthenticationFailureHandler);

        // Add our custom Token based authentication filter
        http.addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }
    
    

}

To do this app I was following this tutorial :
https://www.callicoder.com/spring-boot-security-oauth2-social-login-part-2/

Anybody knows what could be the problem?
Thanks

答案1

得分: 17

看起来是缩进问题,security属性必须在spring属性下面,像这样:

spring:
   security:
英文:

Seems like and indentation issue, security property must be beneath the spring property like so

spring:
   security:

答案2

得分: 2

我发现如果发生以下情况,也会出现这种情况:

  • 您的活动 Spring 配置文件未正确定义
  • 默认配置文件缺少 OAuth2 信息(例如客户端 ID 和密钥)。

您可以在我的另一个答案这里阅读相关信息;通过在日志中查找以下错误消息,即可进行排查:

未设置活动配置文件,回退到一个默认配置文件:“default”
英文:

I found this also happens if:

  • Your active spring profile isn't defined correctly
  • The default profile is missing the OAuth2 information (e.g. client ID and secret).

You can read a bit about it in my other answer here; it's sufficient to triage this by looking for this error message in the logs:

No active profile set, falling back to 1 default profile: "default"

答案3

得分: -2

作者在以下的 GitHub 链接中提供了完整的源代码。下载代码并构建它,然后尝试运行它。在这个项目中有两种类型的工程,一种是 Java 类型的,你需要使用 Maven 构建,另一种是 React 项目,你需要使用 yarn 构建,就像 npm 包管理器一样。

要运行项目 "react-social",你需要使用以下命令构建:yarn install && yarn build && yarn start。要构建其他基于 Spring 的项目 "spring-social",你需要使用命令 mvn clean install。你也可以直接运行命令 mvn spring-boot:run

关于如何运行项目的说明作者在 GitHub 上的 ReadMe.md 文件中有提供。我建议先构建并运行基于 Spring 的项目,然后再处理 react-social 项目。

链接:https://github.com/callicoder/spring-boot-react-oauth2-social-login-demo

英文:

The author has given the complete source code in the following github link. Download the code and build it and try to run it. In this project there are two types of project, one is java type which you have to build using maven and another is react project which you have to build using yarn just like npm package manager.

To run the project "react-social", you have to build using the command yarn install && yarn build && yarn start. To build other spring based project "spring-social", you have to use the command mvn clean install. You can also run the command directly mvn spring-boot:run.

The author has given instruction about to run the project in ReadMe.md file in github. I would suggest first build and run the spring based project and then react-social project.

https://github.com/callicoder/spring-boot-react-oauth2-social-login-demo

huangapple
  • 本文由 发表于 2020年4月10日 03:38:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/61128936.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定