물에 살고싶은 개발자

급한대로.. 본문

카테고리 없음

급한대로..

돼지사랑 2024. 11. 19. 15:07

스프링(Spring)에서 CORS 문제를 해결하려면 주로 다음 세 가지 방법 중 하나를 사용합니다. 각 방법은 요구사항에 따라 적절히 선택할 수 있습니다.


1. 전역적으로 CORS 허용하기

스프링 애플리케이션의 모든 API에 대해 CORS를 허용하려면 WebMvcConfigurer를 사용합니다.

예제: WebMvcConfigurer로 전역 설정

java
코드 복사
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 모든 엔드포인트에 대해 허용
                .allowedOrigins("<http://localhost:3000>", "<http://192.168.0.89:3000>") // 허용할 도메인
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 허용할 HTTP 메서드
                .allowCredentials(true) // 쿠키 및 인증 정보 허용
                .allowedHeaders("*") // 모든 헤더 허용
                .exposedHeaders("Authorization"); // 클라이언트에서 접근할 수 있는 헤더
    }
}


2. 컨트롤러 수준에서 CORS 허용

특정 컨트롤러 또는 엔드포인트에만 CORS를 적용하려면 @CrossOrigin 애너테이션을 사용합니다.

예제: 특정 엔드포인트에 CORS 허용

java
코드 복사
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApiController {

    @CrossOrigin(
        origins = "<http://localhost:3000>", // 허용할 도메인
        allowCredentials = "true", // 쿠키 및 인증 정보 허용
        methods = {RequestMethod.GET, RequestMethod.POST} // 허용할 HTTP 메서드
    )
    @GetMapping("/api/cali/cali-store/check/{kioskId}")
    public String checkKiosk(@PathVariable String kioskId) {
        return "{\\"serverId\\" : \\"02001\\"}";
    }
}


3. 필터로 CORS 허용 (저수준 방식)

전역 설정 대신, Spring Filter를 사용하여 CORS 헤더를 응답에 추가하는 방식입니다. 이 방법은 유연하지만, 보통 위 두 가지 방식이 더 권장됩니다.

예제: CORS 필터 추가

java
코드 복사
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CorsFilter implements Filter {

    @Override
    public void doFilter(
        javax.servlet.ServletRequest request,
        javax.servlet.ServletResponse response,
        FilterChain chain
    ) throws IOException, ServletException {

        HttpServletResponse res = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;

        res.setHeader("Access-Control-Allow-Origin", "<http://localhost:3000>");
        res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        res.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
        res.setHeader("Access-Control-Allow-Credentials", "true");

        if ("OPTIONS".equalsIgnoreCase(req.getMethod())) {
            res.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(request, response);
        }
    }
}


4. Spring Security를 사용하는 경우

스프링 시큐리티(Spring Security)를 사용하는 경우, CORS 설정을 추가로 구성해야 합니다.

예제: Spring Security에서 CORS 설정

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.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.cors() // CORS 설정 활성화
            .and()
            .csrf().disable(); // CSRF 비활성화 (테스트 환경)

        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("<http://localhost:3000>"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type"));
        configuration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);

        return source;
    }
}


요약

  1. Spring MVC 전역 설정 (WebMvcConfigurer):
    • 전체 애플리케이션에 대해 CORS를 허용하려는 경우.
  2. @CrossOrigin 애너테이션:
    • 특정 컨트롤러나 엔드포인트에만 적용하려는 경우.
  3. Spring Filter:
    • 더 세부적으로 CORS를 설정하려는 경우.
  4. Spring Security 사용 시:
    • Spring Security와 함께 사용할 경우, SecurityConfig에서 cors()를 활성화하고 CorsConfigurationSource를 추가해야 합니다.

테스트 환경에서만 사용하도록 하며, 프로덕션 환경에서는 보안 정책을 반드시 준수해야 합니다.

Comments