안녕하세요. 오늘은 Spring Security CORS 설정하는 방법에 대해서 알아보겠습니다.
자바와는 다르게 코틀린에서는 권장하는 문법이 조금 달라서 저도 적용하는데 애먹었습니다.
환경
- JDK17
- Kotlin
- Spring Boot 3.2.4
- Spring Security
Configuration 파일 수정
우선 설정 파일을 변경해야 합니다. 코드와 주석 따라서 한번 천천히 확인해 봅시다.
@ComponentScan
@Configuration
@EnableWebSecurity
class SpringConfiguration {
@Bean
@Throws(Exception::class)
fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http
// 아래와 같이 선언해주어야 cors 설정이 적용된다.
// 이렇게 해주지 않으면 cors 설정이 기본값으로만 적용된다.
.cors{}
return http.build()
}
// 위 설정에서 .cors{}를 해주어야만 아래 cors 설정이 적용된다.
@Bean
fun corsConfigurationSource(): CorsConfigurationSource {
val configuration = CorsConfiguration()
// 허용할 URL들
configuration.allowedOrigins = listOf("http://localhost:3000")
// 허용할 Method들
configuration.allowedMethods = listOf("POST", "GET", "DELETE", "PUT")
// 허용할 Header들
configuration.allowedHeaders = listOf("*")
// 세션 쿠키를 유지할 것 인지
configuration.allowCredentials = true
// cors 적용
val source = UrlBasedCorsConfigurationSource()
source.registerCorsConfiguration("/**", configuration)
return source
}
}
이상하게도 .cors{}
라고 해두지 않으면 cors 설정값이 적용되지 않는 것을 확인했습니다. .cors {}
가 없다면 완전 기본값으로 처리되고 모든 요청을 다 틀어막는 것을 경험했습니다.
CORS를 비활성화하고 싶다면 .cors{}
를 .cors { it.disable() }
로 변경하시면 됩니다.
'JVM > Kotlin' 카테고리의 다른 글
Spring Security 세션 로그인 직접 구현하기(Kotlin) (0) | 2025.02.02 |
---|