지난번엔 Spring Security를 통해 CSRF 설정하는 방법을 알아보았다. 이번엔 CORS 설정에 대해서 적어보려고 한다. CORS란 무엇이며 어떻게 설정해야할까?
- 프로토콜, 호스트, 포트 를 통틀어 Origin 이라고 함
- 즉, 여기서 하나라도 다르면 Cross Origin이 됨
- 보안상의 이유로 Cross Origin HTTP Request를 제한함
하지만 한 서버에서 데이터와 정적파일을 같이 렌더링해 사용자의 요청을 처리하는것이 아닌 api 서버를 분리하여 통신한다면 Cross-Origin 이므로 오류가 발생할 것이다.
@RequestMapping("/somePath")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class SomeController {
}
- @CrossOrgin이라는 어노테이션을 사용하여 원하는 메소드나 원하는
mapping에만 사용할 수 있다.- origin: 도메인을 설정하면 해당 도메인은 다른 orgin을 요청을 받을 수 있음
- allowedOrigin: 자원 공유를 허락할 모든 orgin을 지정할 수 있음
- allowedMethods: 허용할 HTTP method를 지정할 수 있음
- allowrdHeaders: 클라이언트 측의 CORS 요청에 허용하는 헤더를 지정
-> 기본적으로 Content-Type, Accept 및 Origin과 같은 간단한 요청 헤더만 허용됨
@RestController
@RequestMapping("/somePath")
public class SomeController {
@CrossOrigin(origins="*")
@RequestMapping(value = "/{something}",method = RequestMethod.DELETE)
public ResponseEntity<String> delete(@PathVariable Long reservationNo) throws Exception{
}
}
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
}
}
registry.addMapping("/**");
- Allow all origins.
- Allow "simple" methods GET, HEAD and POST.
- Allow all headers.
- Set max age to 1800 seconds (30 minutes).
.allowedOrigins("*");
.allowedOrigins("http://localhost:8080", "http://localhost:8081");
.allowedMethods("GET", "POST");
.maxAge(3000);
.allowCredentials(true)
최종 코드를 살펴보면 아래와 같다.
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
..allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}
java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*"since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
해당 오류는 스프링 부트에서 CORS 설정 시, allowCredentials(true)
와 allowedOrigins("*")
를 동시에 사용할 수 없도록 업데이트 되었다.
따라서 allowedOrigins("*")
을 allowedOriginPatterns("*")
로 변경하면 된다.
💡 SecurityFilterChain 메소드에서 cors 설정을 disable 해줘야 한다.
기존엔 .cors().dsiable()로 하였지만 SpringBoot 3.1 이후론 csrf 을 disable 했을때 처럼 cors(AbstractHttpConfigurer::disable)라고 해줘야한다.
@Configuration
public class WebConfig implements WebMvcConfigurer {
/**
* @param registry
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}
@Configuration
@EnableWebSecurity
public class AuthenticationConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.httpBasic(HttpBasicConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable)
.cors(AbstractHttpConfigurer::disable);
return httpSecurity.build();
}
}
해당 글은 CORS
나 CSRF
에 대한 모든 설정을 허용한 경우이다. 사이드 프로젝트나 단순히 테스트, 공부를 위한 경우라면 해당 설정을 적용해도 문제는 없다.
하지만 만약 실제로 서버 배포를 진행한다면 해당 설정을 절대로 그대로 사용하지 말고 각자의 서버 환경에 맞게 변경해주어야 한다.
Spring Security Cors
[Spring Boot] CORS Filter 설정하기 (CORS 오류 해결방법) - Java
[Spring Boot] CORS 설정하기
[Tistory] Spring Boot Cors 설정하기
[Spring Boot] CORS 설정 시 addCorsMappings 관련 에러