[Spring]Spring Security 설정과 OAuth2와 순환 참조 해결

2025. 11. 18. 12:49·cs/dev
728x90

1. 핵심 애노테이션

  • @Configuration

스프링 빈을 등록하거나 설정 파일을 구성하기 위한 애노테이션이다.

  • @EnableWebSecurity

Spring Security 필터를 Spring FilterChain에 등록하여 보안 기능을 활성화한다.

2.Spring Security의 동작 구조

@Configuration
@EnableWebSecurity
public class SecurityConfig{

  @Bean // 패스워드 암호화 관련 메소드
  public PasswordEncoder passwordEncoder(){
      return new BCryptPasswordEncoder();
  }

    @Bean // 시큐리티 대부분의 설정을 담당하는 메소드
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
            // ...
            return http.build();
    }

    // 이외에도 등록해서 사용하면 된다..
}

 

3. Spring Security 변화

3-1.csrf() Deprecated

'csrf()' is deprecated and marked for removal
찾아보니 Spring Security 6.1.0부터는 메서드 체이닝의 사용을 지양하고  람다 기반 함수형 DSL로 설정하는 것을 권장합니다.

 

이유
1.리턴 타입의 명확성
2. 일관성 문제 때문이라고 한다.

3-2.WebSecurityConfigurerAdapter 사용 중단

스프링 공식 블로그 2022년 2월 21일 글에서 WebSecurityConfigurerAdapter를 사용하는 것을 권장하지 않는다고 컴포넌트 기반 설정으로 변경할것을 권장합니다.

 

  • 전(extends WebSecurityConfigurerAdapter)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }
}
  • 후
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    @Bean
    AuthenticationManager authenticationManager(
            AuthenticationConfiguration authenticationConfiguration
    ) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }
}

 

4.Spring Security의 예외

Security 필터에 의해 발생하는 예외는 2가지가 있다.

  • 인증(Authentication)에 대해서는 AuthenticationException이 발생
  • 인가(Authorization)에 대해서는 AccessDeniedException이 발생

 

5.프로젝트에 Spring Security적용할때 발생한 문제

5-1.Authentication 타입 문제 (UserDetails vs OAuth2User)

Spring Security 적용할 때 circular reference, dependency가 cycle 형성하는 것 해결하기

Authentication에는 2개의 타입이 들어갈 수 있는데 UserDetails, OAuth2User이다.

일반 로그인 시 = UserDetails
OAuth2 로그인 시 = OAuth2User

 

문제점
이때 세션이 2개의 타입으로 나눠졌기 때문에 컨트롤러에서 처리하기 복잡해진다는 문제점이 발생한다!
왜냐하면 일반적인 로그인을 할 때엔 UserDetails 타입으로 Authentication 객체가 만들어지고,
구글 로그인처럼 OAuth 로그인을 할 때엔 OAuth2User 타입으로 Authentication 객체가 만들어지기 때문이다.

 

해결방법
PrincipalDetails에 UserDetails, OAuth2User를 implements한다.
우리는 오직 PrincipalDetails 만 활용하면 된다.

public class PrincipalDetails implements UserDetails, OAuth2User { ... }

 

5-2.  circular dependency 문제

문제점

순환 참조란 Bean A가 Bean B를 필요로 하고, 동시에 Bean B가 Bean A를 필요로 하는 상황을 말합니다.

SecurityConfig
→ PrincipalOAuth2DetailsService
→ BCryptPasswordEncoder
→ SecurityConfig

Description:
The dependencies of some of the beans in the application context form a cycle:
┌─────┐| securityConfig defined in file [/Users/jung/Desktop/ondot_back/out/production/classes/com/ondot/ondot_back/global/config/SecurityConfig.class]↑ ↓| principalOAuth2DetailsService (field private org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder com.ondot.ondot_back.global.config.oauth.PrincipalOAuth2DetailsService.bCryptPasswordEncoder)└─────┘

 

해결방법

순환참조되는 Config 파일을 분리시켜서 PasswordEncoder bean 등록을 분리하면 서비스 간 순환 참조를 방지할 수 있다.

728x90
반응형

'cs > dev' 카테고리의 다른 글

[DB]Redis를 사용하는 이유  (0) 2025.11.21
[리눅스]포그라운드(Foreground)와 백그라운드(Background)  (0) 2025.11.19
[운영체제]뮤텍스(mutex), 세마포어(semaphore), 모니터(Monitor)  (0) 2025.11.17
[Spring]JPA N + 1 문제  (0) 2025.11.09
[Spring] Spring MVC 와 Spring WebFlux 차이  (1) 2025.10.28
'cs/dev' 카테고리의 다른 글
  • [DB]Redis를 사용하는 이유
  • [리눅스]포그라운드(Foreground)와 백그라운드(Background)
  • [운영체제]뮤텍스(mutex), 세마포어(semaphore), 모니터(Monitor)
  • [Spring]JPA N + 1 문제
lakedata
lakedata
lakedata 님의 블로그 입니다.
  • lakedata
    lakedata 님의 블로그
    lakedata
  • 전체
    오늘
    어제
    • 분류 전체보기 (188)
      • cs (82)
        • dev (28)
        • sec (29)
        • ops (25)
      • 자격증 (32)
        • 정보처리기사 (20)
        • 정보보안기사 (1)
        • aws dva (6)
        • aws dop (2)
      • IT서적 (27)
        • 클린아키텍처 (10)
        • 객체지향의사실과오해 (7)
        • 오브젝트 (10)
      • 코테 (42)
        • 알고리즘 (20)
        • 백준 (13)
        • 프로그래머스 (7)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • github
  • 공지사항

  • 인기 글

  • 태그

    SQL
    docker
    알고리즘
    CS
    Spring
    AWS
    Java
    Security
  • 최근 댓글

  • 최근 글

  • 반응형
    250x250
  • hELLO· Designed By정상우.v4.10.3
lakedata
[Spring]Spring Security 설정과 OAuth2와 순환 참조 해결
상단으로

티스토리툴바