인프런 영문 브랜드 로고
인프런 영문 브랜드 로고

인프런 커뮤니티 질문&답변

신석균님의 프로필 이미지
신석균

작성한 질문수

스프링 시큐리티 OAuth2

자체 로그인과 소셜 로그인 동시 설정 문의

해결된 질문

작성

·

1.7K

0

자체 인증과 OAurh2 로 구글 자원 인가 설정을 진행하였습니다.

Spring Security 기본 설정에 oauth2Login 만 활성화 하면 Spring Boot 가 기본으로 설정하는 로그인 화면이 나옵니다.

 

  • Spring Security 설정

    • 구글 계정으로 시스템 인증까지는 필요 없어 access token 받는것까지만 진행

    @Bean
    SecurityFilterChain configureHttp(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.oauth2Login(Customizer.withDefaults());
        return httpSecurity.build();
    }

 

하지만 기존 Spring Security 설정에 oauth2Login 를 활성화 하면 404 에외가 발생하고 있고 있어 디버깅 해보니 강의에 설명된 Spring Security의 OAuth2 Client 관련 필터에 진입하지 못하고 있습니다.

 

  • Spring Security 설정

    @Bean
    SecurityFilterChain configureHttp(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
            .headers()
                .frameOptions()
                    .disable()
            .and()
            .httpBasic()
                .disable()  // rest api 이   므로 기본설정 사용안함..
            .csrf()
                .disable()  // CSRF 설정 Disable
            .cors()
            .and()
                .exceptionHandling()
                    .authenticationEntryPoint(authenticationErrorHandler) // 인증 예외 처리
                    .accessDeniedHandler(jwtAccessDeniedHandler) // 인사 예외 처리
            .and()
                .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // JWT token으로 인증하여 세션을 사용하지 않기 때문에 세션 설정을 Stateless 로 설정
            .and()
                .authorizeRequests() // 권한을 설정
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()   // CORS preflight 요청은 인증 처리를 하지 않는다.
                // 인증이 필요 없는 URI Pattern
                .antMatchers("/openapi/**").permitAll()
                .antMatchers("/**/login/**", "/**/mlogin/**").permitAll()
                .antMatchers("/moblmdm/**").permitAll()
                .antMatchers("/secuCert/**").permitAll()
                .antMatchers("/moblview/**", "/moblsecu/**").permitAll()
                .antMatchers("/websocket/**").permitAll()
                // ADMIN Role을 가진 경우에만 접근을 허용한다.
                //.antMatchers("/mng/**").hasAnyRole("ADMIN")
                .anyRequest().authenticated()
            .and()
                .apply(securityConfigurerAdapter());

        httpSecurity.oauth2Login(Customizer.withDefaults());

//        httpSecurity
//            .oauth2Login()
//            .authorizationEndpoint()
//            .authorizationRequestResolver((new CustomOAuth2AuthorizationRequestResolver(clientRegistrationRepository, DEFAULT_AUTHORIZATION_REQUEST_BASE_URI)))
//            .and()
//            .userInfoEndpoint()
//            .userService(new CustomOAuth2UserService());


        return httpSecurity.build();
    }

 

질문) 자체 로그인 설정과 소셜 로그인을 동시에 사용 할 수 있는 설정을 문의 드립니다.

 

 

참고로 자체 로그인 설정과 소셜 로그인 설정을 분리하고 아래와 같이 소설 로그인 설정에 우선 순위를 주면 소셜 로그인 기능은 활성하 되는데 존 자체 로그인 기능은 비활성화 됩니다.

    @Bean
    @Order(0)
    SecurityFilterChain configureOauth(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
            .oauth2Login()
//                .loginPage("/login")
//                .failureUrl("/login")
            .authorizationEndpoint()
            .authorizationRequestResolver((new CustomOAuth2AuthorizationRequestResolver(clientRegistrationRepository, DEFAULT_AUTHORIZATION_REQUEST_BASE_URI)))
            .and()
            .userInfoEndpoint()
            .userService(new CustomOAuth2UserService());


        return httpSecurity.build();

답변 1

0

정수원님의 프로필 이미지
정수원
지식공유자

내용에 대한 이해는 대략 했는데 실제 코드를 실행해 봐야 정확한 원인을 알 수 있을 것 같습니다.

가능하시다면 깃헙 소스 공유 부탁드립니다.

그리고 자체 로그인이라 하시면 어떤 인증을 의미하신는가요?

필터기반으로 JWT 인증방식의 기능을 구현하신건가요?

참고로

섹션 9. OAuth 2.0 Client - Social Login (Google, Naver, KaKao) + FormLogin
  - OAuth 2.0 Social Login 연동 구현 (5)
  - OAuth 2.0 Social Login 연동 구현 (6)

에 보시면 자체 로그인(FormLogin) 과 소셜 로그인을 통합하여 인증을 처리하는 내용을 설명하고 있으니 참고해 주시기 바랍니다.

신석균님의 프로필 이미지
신석균
질문자

일단은 해결하였습니다. 답변주셔서 감사합니다.

원인은
Spring Boot 2.6.13에서서 소스를 공개하기 위하여 회사 업무에 관련괸 소스를 제외하면서 JSP 사용을 위한 설정을 제외하니 OAuth 2 Client Flitter 들이 정상적으로 실행되어 JSP 설정을 추가하니 되었을OAuth 2 Client Flitter 가 실행되지 않아서 강의의 내용에서 사용된 버전과 동일한 2.7.5에서서는 JSP 사용을 위한 설정이 있어고 이상없이 동작하고 있습니다.

다만 ,
OAuth 2 Client 동작과 JSP 는 무관하고 Spring Security 5.7 과 Spring Boot 2.7 변경 내역을 살펴 보아도 JSP 관련 패치는 없어 이상하기는 합니다.

신석균님의 프로필 이미지
신석균

작성한 질문수

질문하기