Backend/Spring

[Springboot] SpringBoot Security에서 CORS 전체 허용

얌얌념념 2022. 11. 2. 14:17

전체 코드

## SecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
	    .cors()
	        .configurationSource(corsConfigurationSource())
	        .and()
	    .sessionManagement()
	        ...
	    .csrf()
	        .disable()
	    .formLogin()
	        .disable()
	    .httpBasic()
	        .disable()
	    .exceptionHandling()
	        ...
	    .authorizeRequests()
	        ...
	    .oauth2Login()
	        ...
	        .successHandler(oAuth2AuthenticationSuccessHandler)
	        .failureHandler(oAuth2AuthenticationFailureHandler);

    http.addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}

// CORS 허용 적용
@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();

    configuration.addAllowedOriginPattern("*");
    configuration.addAllowedHeader("*");
    configuration.addAllowedMethod("*");
    configuration.setAllowCredentials(true);

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

corsConfigurationSource 함수에서

configuration.addAllowedOriginPattern("*");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
configuration.setAllowCredentials(true);

모두 허용해준 뒤

configure 함수에서 cors에 해당 설정을 적용해주면 된다.

http
  .cors()
      .configurationSource(corsConfigurationSource())
      .and()