728x90
CORS란?
CORS 설명 링크 : https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
목적
: 애플리케이션 간에 출처(Origin)가 다를 경우 스크립트 기반의 HTTP 통신(XMLHttpRequest, Fetch API)을 통한 리소스 접근이 제한 되는데, CORS는 출처가 다른 스크립트 기반 HTTP 통신을 하더라도 선택적으로 리소스에 접근할 수 있는 권한을 부여하도록 브라우저에 알려주는 정책
* 로컬 환경에서 Postman을 사용하여 애플리케이션의 엔드포인트를 호출할 경우에는 CORS 설정이 필요없음
* 프런트엔드 웹앱과의 HTTP 통신에서 에러를 만나게 될 수 있음
적용방법
1. webConfig로 일괄 관리
@Configuration
public class webConfig implements WebMvcConfigurer { // Mvc 모델 내 Web관련 자동 구성 지원하는 인터페이스
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // CORS를 적용할 URL패턴을 정의할 수 있습니다.
.allowedOrigins("*") // 자원 공유를 허락할 Origin을 지정할 수 있습니다. ex) allowedOrigins("http://localhost:8080", "http://localhost:8081");
.allowedMethods("*"); // 허용할 HTTP method를 지정할 수 있습니다. ex) allowedMethods("GET", "POST")
// .maxAge(3000); // 원하는 시간만큼 pre-flight 리퀘스트를 캐싱 해둘 수 있습니다.
/*
addMapping default값
Allow all origins.
Allow "simple" methods GET, HEAD and POST.
Allow all headers.
Set max age to 1800 seconds (30 minutes).
*/
}
}
2. 애너테이션을 이용한 개별 관리
: 적용할 Controller 클래스 레벨 혹은 핸들러 메서드에 적용
@CrossOrigin(origins = "*", allowedHeaders = "*")
3. SecurityFilter에 CorsFilter 추가하여 관리
(section4 => JWT 인증 => JWT적용을 위한 사전 작업 부분)
@Configuration
public class SecurityConfiguration {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.headers().frameOptions().sameOrigin()
.and()
.csrf().disable()
.cors(withDefaults()) // <= cors를 default값으로 적용
.formLogin().disable()
.httpBasic().disable()
.authorizeHttpRequests(authorize -> authorize
.anyRequest().permitAll()
);
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
// CORS filter부분
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET","POST", "PATCH", "DELETE"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
참고 링크 : https://dev-pengun.tistory.com/entry/Spring-Boot-CORS-%EC%84%A4%EC%A0%95%ED%95%98%EA%B8%B0
728x90
'Java & Spring > 프로젝트 기본 설정' 카테고리의 다른 글
[Docker] Keycloak 사용하기 - 진행중 (0) | 2023.08.30 |
---|---|
[GitHub] 템플릿 레포지토리(Template repository) 만들기 (0) | 2023.05.25 |
[SpringBoot] API 문서화 세팅 (asciidoctor) (0) | 2022.11.04 |
[SpringBoot] 프로젝트 워크 플로우 (0) | 2022.11.03 |
[SpringBoot] application.yml 설정 저장 (0) | 2022.11.02 |