Web/Spring Security

Spring Security 6.x.x CORS 설정

조용우 2025. 2. 27. 18:29

SecurityConfig.java

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        ...
        http
            .cors(corsCustomizer -> corsCustomizer.configurationSource(new CorsConfigurationSource() {

                @Override
                public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {

                    CorsConfiguration configuration = new CorsConfiguration();
					
                    // 프론트 서버 주소
                    configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
                    // GET, POST, 등 요청
                    configuration.setAllowedMethods(Collections.singletonList("*"));
                    // 쿠키, Authorization 인증 헤더, TLS client certificates(증명서)를 내포하는 자격 인증 정보
                    configuration.setAllowCredentials(true);
                    // 받을 수 있는 헤더 값
                    configuration.setAllowedHeaders(Collections.singletonList("*"));
                    configuration.setMaxAge(3600L);
					
                    // 백엔드에서 프론트로 보낼 데이터들
                    configuration.setExposedHeaders(Collections.singletonList("Set-Cookie"));
                    configuration.setExposedHeaders(Collections.singletonList("Authorization"));

                    return configuration;
                }
            }));

        ...

        return http.build();
    }

}

 

CorsMvcConfig.java

@Configuration
public class CorsMvcConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry corsRegistry) {
        corsRegistry
            // CORS를 적용할 URL 패턴
            .addMapping("/**")
            // 응답에 노출되는 헤더
            .exposedHeaders("Set-Cookie")
            // 자원 공유를 허락할 origin (프론트)
            .allowedOrigins("http://localhost:3000");
    }
}