[펌글] Spring Security 에서의 CORS 설정

By | 6월 29, 2021

spring security config 클래스


@EnableWebSecurity
public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {

    ...

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
          ...
            .and()
            .authorizeRequests()
            .requestMatchers(CorsUtils::isPreFlightRequest).permitAll() // cors setting 1
            ...
            .and().cors(); // cors setting 2
    }

     // cors setting 3
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {

        CorsConfiguration configuration = new CorsConfiguration();

        // configuration.addAllowedOrigin("*");
        configuration.addAllowedOrigin("http://localhost:3000");

        configuration.addAllowedMethod("*");
        configuration.addAllowedHeader("*");
        configuration.setAllowCredentials(true);
        configuration.setMaxAge(3600L);

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

        return source;
    }
    ...

}


교훈

  1. spring security 를 사용할 때는 기존에 사용하던 CORS 필터 등을 사용하지 말자.
  2. 원문 작성자님 감사합니다 ^^
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments