【问题标题】:Spring Boot CORS enable through configurationSpring Boot CORS 通过配置启用
【发布时间】:2020-01-09 00:39:23
【问题描述】:

我已经阅读了很多关于春季(启动)中 CORS 的帖子,但没有人能回答我的问题,但也许我只是错过了答案,所以请耐心等待。 我有一个目前仅用于服务器到服务器调用的 REST Web 服务。我现在想打开一些端点直接从浏览器调用,而不是从同一个域调用,因此是 CORS。我通过做两件事使它适用于某些端点: 1.在我的WebSecurityConfigurerAdapter中启用OPTIONS:

http.authorizeRequests()
   .mvcMatchers(HttpMethod.OPTIONS, 
                "/endpont1", 
                "/endpoint2")
   .permitAll()

2。为这些端点将以下注释添加到我的@GetMapping

@CrossOrigin(origins = "${cors.origin}", allowCredentials = "true", 
                         exposedHeaders = ResponseUtils.CONTENT_DISPOSITION)
@GetMapping("/endpoint1")

问题是,据我了解文档,将 origins 留空允许 CORS 用于任何域。如果我不需要 CORS,我不想允许 OPTIONS。

通过属性文件进行配置的最佳方法是什么?

“嵌入式”application.properties 应该禁用它,但如果租户想要启用它,我们可以提供额外的 application-tenant.properties,我们可以在其中为某些域启用它并使用适当的配置文件启动应用程序。

编辑:我在另一篇看起来很有趣的帖子中找到了一个答案,也许我可以有条件地做到这一点: https://stackoverflow.com/a/43559288/3737177

【问题讨论】:

    标签: spring-boot cors


    【解决方案1】:

    经过几次尝试和错误,我找到了一个基于this 答案的可行解决方案:

    @Configuration
    @EnableConfigurationProperties
    @Order(1)
    public class EndpointSecurityConfiguration extends WebSecurityConfigurerAdapter {
    
        @Autowired
        private RequestMatcher requestMatcher;
    
        @Value("${cors.origins:}")
        private String corsOrigins;
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            if (StringUtils.isNotBlank(corsOrigins)) {
                http.cors().configurationSource(buildConfigurationSource());
            }
            http.requestMatchers().mvcMatchers("/endpoint1", "/pendpoint2")
            .and().csrf().requireCsrfProtectionMatcher(requestMatcher)
            .and().authorizeRequests().anyRequest()
                    .hasAnyRole(SecurityConfiguration.ROLE_ENDPOINT_USER, SecurityConfiguration.ROLE_ADMIN)
            .and().httpBasic();
        }
    
        private CorsConfigurationSource buildConfigurationSource() {
            CorsConfiguration configuration = new CorsConfiguration();
            configuration.setAllowedOrigins(Arrays.asList(corsOrigins.split(",")));
            configuration.setAllowedMethods(Arrays.asList("GET");
            configuration.setAllowedHeaders(Arrays.asList("authorization"));
            configuration.setAllowCredentials(true);
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/endpoint1", configuration);
            source.registerCorsConfiguration("/endpoint2", configuration);
            return source;
        }
    
    }
    

    如果application-tenant.properties 中有cors.origins 属性,则启用CORS 并配置允许的方法和标头。 CSRF 也为同源请求启用。

    【讨论】:

      【解决方案2】:

      事实是,您无法使用application.properties 文件设置全局 CORS 配置。您必须按照here 的描述使用 JavaConfig。

      implements WebMvcConfigurer
      

      并覆盖下面的方法

       @Override
          public void addCorsMappings(CorsRegistry registry) {
              registry.addMapping("/api/**")
                  .allowedOrigins("http://domain4.com")
                  .allowedMethods("PUT", "DELETE")
                  .allowedHeaders("header1", "header2", "header3")
                  .exposedHeaders("header1", "header2")
                  .allowCredentials(false).maxAge(4200);
          }
      

      或者 在Application.java中添加以下代码sn-p

      @Bean
          public WebMvcConfigurer corsConfigurer() {
              return new WebMvcConfigurerAdapter() {
                  @Override
                  public void addCorsMappings(CorsRegistry registry) {
                      registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
                  }
              };
          }
      

      我认为通过这种方式,您可以在属性文件中添加属性并在此处的代码中使用这些属性,并且您可以根据不同的风格覆盖这些属性。

      【讨论】:

        猜你喜欢
        • 2017-08-10
        • 2021-06-14
        • 2018-11-16
        • 2018-06-21
        • 2018-09-24
        • 1970-01-01
        • 2021-04-03
        • 2016-06-26
        相关资源
        最近更新 更多