如何在Spring启动时在Spring Security级别启用CORS

我正在使用Spring Boot应用程序,该应用程序使用Spring Security。 我已经尝试过@CrossOrigin来启用cors,但它没有用。

如果你想找到我的错误请参考

Spring Blogs表示,当我们使用Spring安全时 ,我们必须在春季安全级别启用cors

我的项目如下。

任何人都可以解释我应该在哪里放置这些配置以及如何找到弹簧安全级别。

这是一种通过Spring BOOT 1.5使Spring Security 4.1支持CROS的方法

@Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH"); } } 

 @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // http.csrf().disable(); http.cors(); } @Bean public CorsConfigurationSource corsConfigurationSource() { final CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(ImmutableList.of("*")); configuration.setAllowedMethods(ImmutableList.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH")); configuration.setAllowCredentials(true); configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type")); final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } } 

如果您更喜欢使用CORS全局配置,则可以如下声明CorsConfigurationSource bean:

 @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and()... } @Bean CorsConfigurationSource corsConfigurationSource() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues()); return source; } } 

有关spring boot项目示例的进一步参考1) https://hellokoding.com/registration-and-login-example-with-spring-security-spring-boot-spring-data-jpa-hsql-jsp/或2) http ://www.mkyong.com/spring-boot/spring-boot-spring-security-thymeleaf-example/