CORS(Cross Origin Resource Sharing): 도메인이 다른 자원에 리소스를 요청할 때 접근 권한을 부여하는 메커니즘
친구의 물건을 쓰려면 친구가 제한하는 규약안에서 사용해야 하듯,
다른 도메인의 자원을 쓰려면 자원의 주인이 허락한 규약을 지켜야 하는 것이고 이러한 규약을 표준화한 것이 CORS이
여기서 말하는 도메인이란 Resource를 의미하며 프로토콜, 호스트, 포트를 의미한다.
(ex. http : 프로토콜, localhost : 호스트, 8080: 포트)
- 프로토콜 - http와 https
- 도메인 - domain.com, other-domain.com
- 포트 번호 - 8080, 7070
위의 3개가 같아야 같은 출처이다.
CORS ERROR 해결방법
1. Spring Security를 사용하여 CORS를 구성하는 방법
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
...
.cors(corsConfig -> corsConfig.configurationSource(corsConfigurationSource()))
...
);
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
configuration.setAllowedMethods(Arrays.asList("GET","POST", "PUT", "DELETE"));
configuration.setAllowedHeaders(Arrays.asList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
위의 코드는
1. "http://localhost:3000" 으로부터 온 요청만 허용하며 다른 도메인의 요청은 거부한다.
2. GET, POST, PUT, DELETE 메서드만 허용한다.
3. "*" (와일드카드)를 사용하여 모든 헤더를 허용한다.
4. 위에서 구성한 `CorsConfiguration` 객체를 모든 엔드포인트 및 경로에 대해 CORS 정책을 적용시킨다.("/**")
2. Servlet Filter를 사용한 커스텀한 CORS 설정
public class CustomCorsFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpServletRequest httpRequest = (HttpServletRequest) request;
httpResponse.setHeader("Access-Control-Allow-Origin", "http://localhost:3000"); // 허용할 도메인 설정
httpResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE"); // 허용할 메서드 설정
httpResponse.setHeader("Access-Control-Allow-Headers", "*"); // 허용할 헤더 설정
httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); // 자격 증명 허용 설정
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// 필요한 경우 초기화 작업 수행
}
@Override
public void destroy() {
// 필요한 경우 리소스 해제
}
}
3. WebMvcConfigurer를 구현하여 CORS 설정
Spring MVC의 `WebMvcConfigurer`를 구현하여 CORS 설정을 커스터마이징할 수 있다.
@Configuration
public class CustomCorsConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000") // 허용할 도메인 설정
.allowedMethods("GET", "POST", "PUT", "DELETE") // 허용할 메서드 설정
.allowedHeaders("*") // 허용할 헤더 설정
.allowCredentials(true); // 자격 증명 허용 설정
}
}
이후에 `addCorsMappings` 메서드를 통해 특정 URL 패턴 또는 모든 요청에 대한 CORS 설정을 정의하고, 이 설정을 위한 `WebMvcConfigurer` 구현 클래스를 만든 후 Spring 컨텍스트에 등록하면 된다.
4. Controller 클래스에 @Crossorigin 어노테이션을 작성
'Springboot' 카테고리의 다른 글
[Springboot] RefreshToken Redis에 저장하기 (0) | 2023.07.19 |
---|---|
[Springboot] DAO, DTO, VO (0) | 2023.07.18 |
[Springboot] Handler, @ExceptionHandler, @ControllerAdvice (1) | 2023.07.11 |
[Springboot] 관계 매핑(ORM; Object Relational Mapping) N:M (0) | 2023.07.07 |
[Springboot] Security (0) | 2023.07.01 |