【问题标题】:global cors configuration does not work in spring boot but indivisual @CrossOrigins work全局 cors 配置在 Spring Boot 中不起作用,但 indivisual @CrossOrigins 工作
【发布时间】:2019-11-13 04:00:00
【问题描述】:

我有以下配置:

@Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST","HEAD","DELETE","PUT"));
        configuration.setMaxAge(1l);
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

和安全配置:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .cors()
            .and()
            .csrf()
            .disable()
            .exceptionHandling()
            .authenticationEntryPoint(unauthorizedHandler)
            .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and().authorizeRequests()
            .antMatchers(
                "/auth/**"
            ).permitAll()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .anyRequest().authenticated()
            ;
}

但这种组合不起作用。如果我删除 CorsConfigurationSource corsConfigurationSource() 块并添加 @CrossOrigin(origins = "*", maxAge = 1) cors 问题就会消失!

但是我想全局注册cors,有什么问题?

我使用 spring boot 版本 2,带有 spring security 和一些 rest 控制器。

(maxAge=1) 添加是因为浏览器缓存浪费了我很多时间!

(如果浏览器有任何机会跳过预检步骤,为什么服务器在实际调用中不检查来源?必须通过浏览器在服务器或客户端检查?)

【问题讨论】:

  • 通过添加此属性进行检查。 configuration.setAllowedHeaders(Arrays.asList("*"));
  • 有效!把它写成答案

标签: spring-boot cors


【解决方案1】:

通过添加此属性进行检查。

configuration.setAllowedHeaders(Arrays.asList("*"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-16
    • 2019-08-25
    • 1970-01-01
    • 2019-10-25
    • 2019-08-25
    • 2016-10-25
    • 2017-10-08
    • 1970-01-01
    相关资源
    最近更新 更多