Cross-Origin Resource Sharing(CORS) 오류 날 때 Spring Security에서 해결

skyju·2023년 4월 4일

Spring

목록 보기
7/7

CORS?

  • Cross-Origin Resource Sharing(CORS)
  • 도메인, 포트, 프로토콜이 다를 때 발생한다.
  • nginx의 설정을 기억해보자
  • 예를들어 https://domain-a.com의 프론트 엔드 javascript코드가 XMLHttpRequest를 사용하여 https://domain-b.com/data.json을 요청하는 경우

문제의 발생

  • 프론트와 백엔드 서버를 따로 AWS 상에 띄우고 요청을 보내며 CORS 오류가 발생하기 시작했습니다.
    Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: Response to preflight request doesn't pass access control check : No 'Access-Control-Allow-Origin' header is present on the request resource.
  • 오류는 친절하게 자신이 CORS 오류임을 밝히고 있습니다..

문제의 해결

  • 백엔드 서버를 Spring Security 전략을 사용하였기 때문에, Spring Security에서 CORS 에러를 잡을 수 있었습니다.
@Bean
  public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.csrf().disable() //REST API 통신만 하는 Server 이므로 Crsf 사용 해체
            .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
            .exceptionHandling()
            .authenticationEntryPoint(jwtAuthenticationEntryPoint)
            .accessDeniedHandler(jwtAccessDeniedHandler)
            // iframe 접근 허용
            .and()
            .headers()
            .frameOptions()
            .sameOrigin()
            // 세션을 사용하지 않기 때문에 STATELESS로 설정
            .and()
            .sessionManagement()
 			.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**").permitAll()
            .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
            .antMatchers("/auth/**").authenticated()
            .antMatchers("/api/**").permitAll()
            .anyRequest().permitAll()
            .and()
  			.cors().configurationSource(corsConfigurationSource())
            .and()
            .apply(new JwtSecurityConfig(jwtTokenProvider));
    return httpSecurity.build();
  }

  @Bean
  public CorsConfigurationSource corsConfigurationSource() {
	  CorsConfiguration config = new CorsConfiguration();
      config.setAllowCredentials(true); // json을 자바스크립트에서 처리할 수 있게 설정
      config.addExposedHeader("accessToken"); // 노출할 헤더 설정
      config.addExposedHeader("refreshToken"); // 노출할 헤더 설정
      config.addAllowedOriginPattern("*"); // 모든 ip의 응답을 허용
      config.addAllowedHeader("*"); // 모든 header의 응답을 허용
      config.addAllowedMethod("*"); // 모든 post, put 등의 메서드에 응답을 허용
      UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
      source.registerCorsConfiguration("/**", config);    // 모든 경로에 Cors설정
      return source;
  }
  • 중요한 점은 CorsConfigurationSource를 작성하고 Cors로 등록해주는 점 정도 입니다.
profile
https://github.com/skyju

0개의 댓글