Spring Security + JWT 8

johaS2·2025년 2월 4일

CORS 설정

  • SecurityConfig에 추가
http
                .cors((corsCustomizer -> corsCustomizer.configurationSource(new CorsConfigurationSource() {

                    @Override
                    public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {

                        CorsConfiguration configuration = new CorsConfiguration();

                        // 허용할 출처(도메인)를 지정
                        configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
                        // 허용할 HTTP 메소드 설정(GET, POST, PUT 등)
                        configuration.setAllowedMethods(Collections.singletonList("*"));
                        // 자격 증명을 허용할지 여부 설정 (쿠키나 인증 정보 포함)
                        configuration.setAllowCredentials(true);
                        // 허용할 헤더 설정
                        configuration.setAllowedHeaders(Collections.singletonList("*"));
                        // 요청을 보낼 수 있는 시간(초)
                        configuration.setMaxAge(3600L);
                        // 프론트엔드에서 클라이언트가 읽을 수 있는 헤더 설정
                        configuration.setExposedHeaders(Collections.singletonList("Authorization"));

                        return configuration;
                    }
                })));

CORS ?

  • 한 도메인에서 실행되는 웹 애플리케이션이 다른 도메인의 자원에 접근할 수 있도록 허용하는 메커니즘
  • 예로 프론트는 localhost:3000에서 실행되고 백엔드는 8080에서 실행되는 경우
    CORS를 설정하지 않으면 프론트에서 백으로 API 요청을 보낼 때 브라우저가 CORS 에러를 발생시킵니다
  • 따라서, CORS 설정은 웹 애플리케이션에서 클라이언트와 서버 간의 자원 공유를 허용하기 위한 설정

CorsMvcConfig 생성

@Configuration
public class CorsMvcConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry corsRegistry) {

        corsRegistry.addMapping("/**")
                .allowedOrigins("http://localhost:3000");
    }
}

Spring MVC의 CORS 설정

  • addCorsMappings 메서드를 사용
  • Security Filter Chain에 걸리지 않는 요청에도 CORS 정책을 적용할 수 있음

왜 두 개를 함께 설정해야하냐!?

  • http.cors() 설정은 Spring Security의 필터가 적용되는 API 요청에 대해서만 동작하고 WebMvcConfigurer의 addCorsMappings 설정은 Spring Security를 거치지 않는 요청에도 CORS를 적용한다
    즉, 확실하게 하려고 ㅎ_ㅎ
profile
passionate !!

0개의 댓글