개발/전자정부프레임워크
RESTful API에 CORS 설정 적용하기
꿈꾸는법사
2024. 12. 28. 19:42
반응형
오늘은 RESTful API 개발 시 자주 직면하게 되는 CORS(Cross-Origin Resource Sharing) 문제를 해결하는 방법에 대해 알아보겠습니다. CORS는 보안 메커니즘으로, 브라우저가 다른 도메인에서 리소스를 요청할 때 서버에서 허용 여부를 명시해야 합니다.
1. CORS란 무엇인가?
- CORS (Cross-Origin Resource Sharing): 한 도메인에서 실행 중인 웹 애플리케이션이 다른 도메인의 리소스에 접근할 수 있도록 허용하는 보안 기능입니다.
- 예를 들어, http://localhost:3000에서 실행 중인 프론트엔드가 http://localhost:8080의 API에 요청할 경우, 서버가 이 요청을 명시적으로 허용해야 합니다.
2. CORS 이슈 발생 사례
다음과 같은 요청을 보낼 때 CORS 문제가 발생할 수 있습니다:
- 서버와 클라이언트가 다른 포트를 사용할 경우
- 클라이언트: http://localhost:3000
- 서버: http://localhost:8080
- 클라이언트에서 Fetch API 또는 Axios를 사용해 요청할 때
- 브라우저는 보안상의 이유로 동일 출처(Same-Origin) 요청만 허용합니다.
3. Spring Boot에서 CORS 설정 방법
Spring Boot에서 CORS 문제를 해결하기 위한 방법은 다음과 같습니다.
(1) @CrossOrigin 어노테이션 사용
특정 컨트롤러나 메서드에서 CORS를 허용하려면 @CrossOrigin을 추가합니다.
@RestController
@RequestMapping("/api")
public class ApiController {
@CrossOrigin(origins = "http://localhost:3000") // 허용할 도메인 명시
@GetMapping("/data")
public String getData() {
return "Hello from server!";
}
}
(2) 전역 CORS 설정
모든 요청에 대해 CORS를 허용하려면 Spring Security의 설정 파일에 등록합니다.
SecurityConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class SecurityConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOrigin("http://localhost:3000"); // 허용할 도메인
configuration.addAllowedMethod("*"); // 모든 HTTP 메서드 허용
configuration.addAllowedHeader("*"); // 모든 헤더 허용
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return new CorsFilter(source);
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf().disable()
.cors().and() // CORS 필터 적용
.authorizeRequests()
.anyRequest().permitAll();
return http.build();
}
}
4. Postman 또는 브라우저 테스트
- CORS 적용 확인
클라이언트에서 http://localhost:8080/api/data를 호출했을 때 정상적으로 데이터가 반환되는지 확인합니다. - 응답 헤더
응답 헤더에 Access-Control-Allow-Origin이 포함되어 있어야 합니다. - Access-Control-Allow-Origin: http://localhost:3000
5. Axios를 활용한 프론트엔드 요청 예시
import axios from 'axios';
axios.get('http://localhost:8080/api/data', {
headers: {
'Content-Type': 'application/json',
},
})
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error('CORS error:', error);
});
6. 주의사항
- 보안 강화:
- 개발 환경에서는 모든 도메인을 허용(*)할 수 있지만, 프로덕션 환경에서는 특정 도메인만 허용하는 것이 바람직합니다.
- 프리플라이트 요청:
- 브라우저는 일부 요청(POST, PUT 등)에서 프리플라이트 요청을 보냅니다. 이 요청도 허용하도록 설정해야 합니다.
7. 요약
Spring Boot에서 CORS 문제는 간단한 설정으로 해결할 수 있습니다. 클라이언트와 서버 간 통신을 원활히 하기 위해 필요한 CORS 정책을 적절히 설정하는 것이 중요합니다.
반응형