# Springboot 3가지 CROS 설정

## 총3가지 방법 요약

#### CorsFilter 설정

```java
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@SpringBootConfiguration
public class WebGlobalConfig {

    @Bean
    public CorsFilter corsFilter() {

        //CorsConfiguration 개체 생성 후 설정 추가
        CorsConfiguration config = new CorsConfiguration();
        //내보낼 원본 도메인 설정
        config.addAllowedOrigin("*");
        //원본 요청 헤더 정보 내보내기
        config.addAllowedHeader("*");
        //header 의 노출 정보
        config.addExposedHeader("*");
        //허용할 요청 항목들
        config.addAllowedMethod("GET");     //get
        config.addAllowedMethod("PUT");     //put
        config.addAllowedMethod("POST");    //post
        config.addAllowedMethod("DELETE");  //delete
        //corsConfig.addAllowedMethod("*");     //모두허용

        // Cookie 전송여부
        config.setAllowCredentials(true);

        //2. 매핑 경로 추가
        UrlBasedCorsConfigurationSource corsConfigurationSource =
                new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**", config);
        
        return new CorsFilter(corsConfigurationSource);
    }
}
```

{% hint style="info" %}
**SpringBoot2.4.4 이후 버전사용시 아래 에러 나올수 있음.**

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.\
at org.springframework.web.cors.CorsConfiguration.validateAllowCredentials(CorsConfiguration.java:453) \~\[spring-web-5.3.6.jar:5.3.6]

\
allow Credentials가 true일 때 alloed Origins는 이 값을 'Access-Control-Allow-Origin' 응답 헤드에서 설정할 수 없기 때문에 특수 값 '\*'를 포함할 수 없음. 인증 정보 액세스를 허용하려면 소스를 명시적으로 나열하거나 'Allowed Origin Patterns'로 변경.

해결방법: **config.addAllowedOrigin("\*"); --> config.addAllowedOriginPattern("\*"); 로 변경.**
{% endhint %}

#### WebMvcConfigurer 재정의하는 방법

```java
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootConfiguration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //매핑경로 추가 
        registry.addMapping("/**")
                //Cookie 전송여부
                .allowCredentials(true)
                //내보낼 원본 도메인 설정 SpringBoot2.4.4 이하 버전은 .allowedOrigins("*") 사용.
                .allowedOriginPatterns("*")
                //요청 방식을 허용
                .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
                //.allowedMethods("*") //요청 방식을 전부 허용
                //원본 요청 헤더 정보 내보내기
                .allowedHeaders("*")
                //원본 요청 헤더 정보 노출
                .exposedHeaders("*");
    }
}
```

#### @CrossOrigin 어노테이션으로 부분적용

```java
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CrossOrigin {
    @AliasFor("origins")
    String[] value() default {};
    @AliasFor("value")
    String[] origins() default {};
    String[] originPatterns() default {};
    String[] allowedHeaders() default {};
    String[] exposedHeaders() default {};
    RequestMethod[] methods() default {};
    String allowCredentials() default "";
    long maxAge() default -1;
}
```

**이후 사용되는 모든 controller 에 @CrossOrigin 붙여준다.**

```java
@Controller
@RequestMapping("/crostest")
@CrossOrigin(originPatterns = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class ShopController {
    
    @GetMapping("/")
    @ResponseBody
    public Map<String, Object> findAll() {
        return DataSchool.getStudents();
    }
}
```

혹은 사용되는 각각의 메소드에 붙여줘도 된다.

```java
@Controller
@RequestMapping("/crostest")
public class ShopController {

    @GetMapping("/")
    @ResponseBody
    @CrossOrigin(originPatterns = "http://localhost:8080")
    public Map<String, Object> findAll() {
   
        return DataSchool.getStudents();
    }

```

끝!


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blakes-organization.gitbook.io/rainsister/spring/springboot-3-cros.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
