【问题标题】:How to disable CORS in Spring Security within Spring Boot?如何在 Spring Boot 中禁用 Spring Security 中的 CORS?
【发布时间】:2021-06-26 07:02:33
【问题描述】:

我想使用 Spring Security 从 Spring Boot (2.3.3.RELEASE) 中完全删除 CORS。

HttpSecurity 对象有 WebSecurityConfigurerAdapter#configure 方法,我可以在其中调用 cors().disable(),但它似乎不起作用。

class MySecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().disable();
    }
}        

使用上面的 sn-p,我在从前端应用程序访问端点时仍然会遇到 CORS 错误。

我必须从WebMvcConfigurer 接口覆盖addCorsMappings,如下所示????。

这是为什么呢?为什么打http.cors().disable()不够?

class MySecurityConfiguration extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("*")
                .allowedOrigins("*");
    }

【问题讨论】:

  • 您无法在没有配置的情况下启用 CORS。 http.cors().disable() 表示服务器不支持跨域资源共享。
  • @dur 不支持是什么意思?那么它是否应该停止验证与 CORS 相关的标头?谢谢解释????
  • 我编辑了我的评论,这令人困惑。你的问题只是措辞问题。默认情况下不允许 CORS,这意味着不允许共享。您必须通过配置启用 CORS。
  • 我明白了,谢谢@dur ????

标签: java spring spring-boot spring-security cors


【解决方案1】:

您好,您需要在您的 Spring Boot 项目中创建一个全局 cors 配置。创建一个类并使用 @Configuration 对其进行注释。您可以按照下面的示例进行操作。

@Configuration
public class MyConfiguration {

 @Bean
 public WebMvcConfigurer corsConfigurer() {
     return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
             registry.addMapping("/api/**")
               .allowedOrigins("http://domain2.com")
               .allowedMethods("PUT", "DELETE")
               .allowedHeaders("header1", "header2", "header3")
               .exposedHeaders("header1", "header2")
               .allowCredentials(false).maxAge(3600);
       }
    };
  }
}

这里是spring框架提供的完整指南https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

【讨论】:

  • 谢谢 Isa,我已经在问题中放了类似的例子 :)
猜你喜欢
  • 2020-05-29
  • 2021-10-30
  • 2019-07-16
  • 2016-08-26
  • 2021-11-06
  • 2018-08-02
相关资源
最近更新 更多