CORS?
CORS λ, Cross-Origin Resource Sharing, μ¦ μΉ λΈλΌμ°μ μμ μλ‘ λ€λ₯Έ Origin κ°μ Resource μμ²μ μ μ΄νλ λΈλΌμ°μ 보μ μ μ± μ΄λ€.
μ¬κΈ°μ Origin μ protocol, domain(host), port μ μ‘°ν©μ μλ―Ένλ€. μλ₯Ό λ€μ΄,Β http://localhost:3000 κ³ΌΒ http://localhost:8080 μ ν¬νΈκ° λ€λ₯΄κΈ° λλ¬Έμ μλ‘ λ€λ₯Έ Origin μΈ κ²μ΄λ€.
Why using CORS?
μΉ λΈλΌμ°μ λ SOP(Same-Origin Policy) λ₯Ό μ μ©νλ€. μ΄ μ μ± μ μ΄λ€ Origin μμ νΈμΆν Script λ λ€λ₯Έ Origin μμ κ°μ Έμ¨ Resource λ±κ³Όμ μνΈμμ©μ μ ννλ κ²μ΄λ€.
λ§μ½ Spring Boot μμ Thymeleaf λ‘ Front-End λ₯Ό ꡬννλ€κ³ κ°μ νμ. μ΄ μν©μμλ Origin μ΄ λμΌνκΈ° λλ¬Έμ λΈλΌμ°μ μμ SOP Error κ° λ°μνμ§ μλλ€.

κ·ΈλΌ μμ κ°μ΄ Front-End μ Back-End λ₯Ό κ°κ° λ€λ₯Έ μλ²μμ κ°λ°νλ€κ³ κ°μ ν΄λ³΄μ. Spring Boot μ React λ₯Ό μ¬μ©νμ¬ κ°κ° κ°λ°νλ€κ³ νμ λ, μΉ λΈλΌμ°μ μ μ½μ λ‘κ·Έμμ CORS Error λ₯Ό μ½κ² λ§μ£Όν μ μλ€. μ΄λ λΈλΌμ°μ κ° Back-End API μμ²μ λ§λ νμμΈλ°, μ΄λ CORS μ λν μ€μ μ΄ νμνλ€.
How CORS works?
CORS κ° λμνλ λ°©μμ λ€μκ³Ό κ°λ€.
- Front-End μμ Back-End λ‘ μμ²μ λ³΄λΌ λ, λΈλΌμ°μ λ request header μ Origin μ 보λ₯Ό μΆκ°
- Back-End λ response μ
Access-Control-Allow-Originheader λ₯Ό μΆκ°νμ¬, μ΄λ€ Origin μ request λ₯Ό νμ©ν μ§ λͺ μ- λΈλΌμ°μ λ μμ μ Origin κ³Ό, μλ²κ° νμ©ν Origin μ λΉκ΅νμ¬ μ‘°κ±΄μ΄ λ§μΌλ©΄ response data λ₯Ό νμ©, κ·Έλ μ§ μλ€λ©΄ CORS Error λ₯Ό λ°μμν΄
CORS Configuration
CORS λ₯Ό Spring Boot Application μ μ μ©μν€κΈ° μνμ¬λ CORS μ λν μ€μ μ΄ νμνλ€.
Spring Security λ₯Ό μ¬μ©νλ€λ©΄, μ°μ SecurityConfig class μ SecurityFilterChain μμ CORS κ΄λ ¨ μ€μ μ ν΄μ£Όμ΄μΌ νλ€.
@Bean
public SecurityFilterChain filterChain(HttpSecurity http, AuthenticationManager authenticationManager) throws Exception {
http
.cors((cors) -> cors
.configurationSource(new CorsConfigurationSource() {
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
configuration.setAllowedMethods(Collections.singletonList("*"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(Collections.singletonList("*"));
configuration.setMaxAge(3600L);
return configuration;
}
}))
...
}SecurityConfig μ λν μ€μ μ λ³΄ν΅ λ‘κ·ΈμΈ λ±μ μΈκ° λ° μΈμ¦ μμ
μμ μνλλ―λ‘ λλ¨Έμ§ Controller μλ CORS λ₯Ό μ€μ ν΄μ£Όμ΄μΌ νλ€. μ΄λ CorsMvcConfig λ₯Ό ν΅νμ¬ μ€μ ν΄μ€ μ μλ€.
@Override
public void addCorsMappings(CorsRegistry corsRegistry) {
corsRegistry.addMapping("/**")
.allowedOrigins("http://localhost:3000");
}