Spring Security CORS + @Profile 설정 방법 - Profile 별로 CORS 다르게 설정하기
📣

Spring Security CORS + @Profile 설정 방법 - Profile 별로 CORS 다르게 설정하기

Created
2023/10/10
Tags
SpringBoot
SpringSecurity
Debug
 
2023-10-10 @이영훈
 
Spring Security에서 Active Profile 별로 (prod, stage, dev) CORS에서 허용해주는 url을 따로 설정하는 것이 관리하기 편합니다.
  • dev 환경이면 클라이언트도 dev 환경으로 맞추고 URL도 다르기 때문에, 환경별로 허용해야할 CORS URL이 다릅니다.
 
사소하지만 CORS 설정 시 @Profile 을 설정했는데도 정상적으로 동작하지 않았던 짧은 디버깅 과정을 기록으로 남깁니다.
 

CORS + @Profile 설정하는 방법

 
  1. @Profile로 각 환경을 설정합니다
  1. @Bean의 이름을 corsConfigurationSource 로 설정합니다.
    1. 공식문서를 확인해보면, servlet에 CORS 적용하는 방법이 나옵니다.
      여기에서 이름이 corsConfigurationSource인 빈을 사용한다고 안내하고 있습니다.
      Kotlin
      @Configuration
      @EnableWebSecurity
      open class WebSecurityConfig {
          @Bean
          open fun filterChain(http: HttpSecurity): SecurityFilterChain {
              http {
                  // by default uses a Bean by the name of corsConfigurationSource
      						// 기본값으로, 이름이 corsConfigurationSource인 빈을 사용합니다
                  cors { }
                  // ...
              }
              return http.build()
          }
      }
 
 
저는 정책적으로 기본값을 사용하고, 빈 이름을 corsConfigurationSource로 맞추는 방법을 선택했습니다.
  • Convention over Configuration을 따름으로써, 다른 개발자와 협업과 관리가 편리하기 위해서
 
Bean 이름은 기본적으로, method 명과 동일하기 때문에 두 method 모두에 Bean 이름을 수동으로 지정하였습니다.
Kotlin
@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true)
@Configuration
class ProjectConfig {

    @Bean
    fun filterChain(http: HttpSecurity): SecurityFilterChain {
        http.cors { }  // CORS를 설정하였습니다
            .csrf { csrf -> csrf.disable() }
            .sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) }
            .addFilterBefore(exceptionHandlerFilter(), BasicAuthenticationFilter::class.java)
            .addFilterAt(loginAuthenticationFilter(), BasicAuthenticationFilter::class.java)
            .authorizeHttpRequests { it.anyRequest().permitAll() }

        return http.build()
    }

		// bean name이 "corsConfigurationSource" 이어야 합니다
		@Bean("corsConfigurationSource")
    @Profile("prod")
    fun corsConfigurationSourceForProd(): CorsConfigurationSource {
        val configuration = CorsConfiguration().apply {
						allowedOrigins = listOf(
								"https://leedo.me",  // prod 전용 url
            )

            addAllowedMethod("*")
            addAllowedHeader("*")
        }

        return UrlBasedCorsConfigurationSource().apply {
            registerCorsConfiguration("/**", configuration)
        }
    }

		// bean name이 "corsConfigurationSource" 이어야 합니다
    @Bean("corsConfigurationSource")
    @Profile("dev")
    fun corsConfigurationSourceForDev(): CorsConfigurationSource {
        val configuration = CorsConfiguration().apply {
						allowedOrigins = listOf(
								"https://dev.leedo.me",  // dev 전용 url
            )

            addAllowedMethod("*")
            addAllowedHeader("*")
        }

        return UrlBasedCorsConfigurationSource().apply {
            registerCorsConfiguration("/**", configuration)
        }
    }
}