本文介绍了如何在Spring启动时在Spring Security级别启用CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If you want to find my error refer this

说当我们使用 spring security 时,我们必须在春季安全级别启用cors

Spring Blogs says that when we are working with spring security, we must enable cors at spring security level.

我的项目如下。

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

Can anyone explain where should I put those configuration and how to find the spring security level.

推荐答案

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

this is a way to make Spring Security 4.1 support CROS with Spring BOOT 1.5

  @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;
    }
}

这篇关于如何在Spring启动时在Spring Security级别启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 23:07