programing

'org. spring framework' 유형의 콩.security.oauth2.client.registration.'클라이언트 등록 리포지토리'를 찾을 수 없습니다. - Spring Security

codeshow 2023. 8. 10. 21:45
반응형

'org. spring framework' 유형의 콩.security.oauth2.client.registration.'클라이언트 등록 리포지토리'를 찾을 수 없습니다. - Spring Security

스프링 보안이 적용된 스프링 응용 프로그램을 개발하고 구글 로그인을 하고 있는데 응용 프로그램을 실행할 때 다음 오류가 발생합니다.

***************************
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.

내 애플리케이션.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

SecurityConfig 클래스:

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);
    }



}

앱을 하기 위해 저는 이 튜토리얼 https://www.callicoder.com/spring-boot-security-oauth2-social-login-part-2/ 을 따르고 있었습니다.

뭐가 문제인지 아는 사람?감사해요.

그리고 들여쓰기 문제인 것 같습니다. 보안 속성은 스프링 속성 아래에 있어야 합니다.

spring:
   security:

다음과 같은 경우에도 이러한 현상이 발생한다는 것을 발견했습니다.

  • 활성 스프링 프로필이 올바르게 정의되지 않았습니다.
  • 기본 프로필에 OAuth2 정보(예: 클라이언트 ID 및 비밀)가 없습니다.

이에 대한 자세한 내용은 여기 있는 다른 답변에서 확인할 수 있습니다. 로그에서 다음 오류 메시지를 찾아 이 문제를 분류하면 충분합니다.

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

작성자는 다음 github 링크에서 완전한 소스 코드를 제공했습니다.코드를 다운로드하여 빌드하고 실행해 보십시오.이 프로젝트에는 두 가지 유형의 프로젝트가 있습니다. 하나는 maven을 사용하여 구축해야 하는 java 타입과 npm package manager처럼 yarn을 사용하여 구축해야 하는 react 프로젝트입니다.

프로젝트 "react-social"을 실행하려면 다음 명령을 사용하여 빌드해야 합니다.yarn install && yarn build && yarn start다른 스프링 기반 프로젝트 "spring-social"을 구축하려면 다음 명령을 사용해야 합니다.mvn clean install명령을 직접 실행할 수도 있습니다.mvn spring-boot:run.

저자는 ReadMe.md 파일의 github에서 프로젝트를 실행하는 것에 대한 지침을 제공했습니다.저는 먼저 스프링 기반 프로젝트를 구축하고 실행한 다음 반응-사회적 프로젝트를 제안합니다.

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

언급URL : https://stackoverflow.com/questions/61128936/bean-of-type-org-springframework-security-oauth2-client-registration-clientregi

반응형