全局cors配置在Spring Boot中不起作用,但单个@CrossOrigins起作用 [英] global cors configuration does not work in spring boot but indivisual @CrossOrigins work

查看:179
本文介绍了全局cors配置在Spring Boot中不起作用,但单个@CrossOrigins起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下配置:

@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问题将消失!

but this mix does not work. If I remove CorsConfigurationSource corsConfigurationSource() block and add @CrossOrigin(origins = "*", maxAge = 1) cors problems will gone!

但是我想在全球范围内注册cors,这是什么问题?

but I want to register cors globally, what is the problem?

我使用带有弹簧安全性和一些Rest控制器的Spring Boot版本2.

I use spring boot version 2, with spring security and some rest controllers.

(maxAge = 1)由于浏览器缓存而浪费了我很多时间!

(maxAge=1) added because of browser caching that waste a lot of my time!

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

(if by any chance, browser skips preflight step, why server does not check for origin in real call? that must be checked in server or in client by browser?)

推荐答案

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

Check by adding this property.

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

这篇关于全局cors配置在Spring Boot中不起作用,但单个@CrossOrigins起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆