SpringSecurity_CORS 설정
2023. 4. 10. 16:06ㆍSpring
728x90
CORS
- Cross-Origin Resource Sharing Policy
CorsConfigurationSource 사용
- 코드
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.Arrays;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
// CORS 설정
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOriginPatterns(Arrays.asList("*")); // 모든 패턴에 대해 허용
configuration.setAllowedMethods(Arrays.asList("HEAD","POST","GET","DELETE","PUT"));
configuration.setAllowedHeaders(Arrays.asList("*"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.cors(Customizer.withDefaults()) // cors - CorsConfigurationSource 사용하여 설정
.build();
}
참고자료
https://docs.spring.io/spring-security/reference/servlet/integrations/cors.html
'Spring' 카테고리의 다른 글
Spring_JWT Token Setting (0) | 2023.05.15 |
---|---|
Spring Security Swagger 예외처리 (0) | 2023.04.03 |
Spring Swagger (0) | 2023.04.03 |
Spring Security (0) | 2023.04.03 |
JPA Mapping (0) | 2023.03.31 |