# 에러 내용
┌─────┐
| jwtCookieFilter defined in file [D:\2024\sso\build\classes\java\main\com\jwt\sso\example\sso\global\JwtCookieFilter.class]
↑ ↓
| securityConfig defined in file [D:\2024\sso\build\classes\java\main\com\jwt\sso\example\sso\global\SecurityConfig.class] └─────┘
jwt + oauth2 + cookie(jwt filter)를 이용한 기능을 구현하다가 위와 같은 에러가 나왔다.
즉 순환 종속성 에러이다.
=> 순환 종속성은 두 클래스가 서로 종속될 때 발생한다고 한다. 예를 들어 클래스 A에는 클래스 B가 필요하고 클래스 B에도 클래스 A가 필요할 때를 말하는 것이다.
# 에러 코드
아래와 같이 cookie를 통해서, jwt의 token 검증 하는게 있고, 아래 해당 filter를 이용해서 api의 /menu에서 인증을 통해서 값을 허용 시키는 기능이 있을때 에러가 났다.
@Component
public class JwtCookieFilter extends OncePerRequestFilter {
private final JwtDecoder jwtDecoder;
public JwtCookieFilter(JwtDecoder jwtDecoder) {
this.jwtDecoder = jwtDecoder;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
}
}
}
@Configuration
public class SecurityConfig { private final JwtCookieFilter jwtCookieFilter;
public SecurityConfig(JwtCookieFilter jwtCookieFilter) {
this.jwtCookieFilter = jwtCookieFilter;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/menu").authenticated() // /menu는 인증 필요
.anyRequest().permitAll()) // 그 외의 요청은 허용
.addFilterBefore(jwtCookieFilter, UsernamePasswordAuthenticationFilter.class) // 커스텀 필터 추가
.oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())))
.csrf(csrf -> csrf.disable()); // CSRF 비활성화
return http.build();
}
# 해결 :
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/menu").authenticated()
.anyRequest().permitAll())
.addFilterBefore(new JwtCookieFilter(jwtDecoder()), UsernamePasswordAuthenticationFilter.class) // 직접 객체 생성
.oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())))
.csrf(csrf -> csrf.disable());
return http.build();
}
위와 같이 수정.
# 수정한 내용
1. 제거
public SecurityConfig(JwtCookieFilter jwtCookieFilter) {
this.jwtCookieFilter = jwtCookieFilter;
}
2. 직접 객체로 생성
.addFilterBefore(jwtCookieFilter, UsernamePasswordAuthenticationFilter.class)
=>
.addFilterBefore(new JwtCookieFilter(jwtDecoder()), UsernamePasswordAuthenticationFilter.class)
3. jwtCookieFilter 쪽은 그대로 놔둠.
위에 처럼 진행시 정상적으로 순환 종속성 에러 안나고, 쿠키를 이용한 JWT이 정상적으로 검증되어서 받아 왔다.
'error' 카테고리의 다른 글
| [error] intellij lombok 인식 안되는 에러(cannot find symbol ~get) (0) | 2024.12.11 |
|---|---|
| [error react] Module not found: Can't resolve 'web-vitals' 오류 해결 (0) | 2024.12.09 |
| [error] build.gradle.ktx 모든 줄이 빨강으로 나올때(intellij) (0) | 2024.12.03 |
| [error] 502 Bad gateway (0) | 2024.12.02 |
| [error] 한글 .hwpx, hwp등 검은색 화면 나올때 (2) | 2024.11.22 |