CORS 策略:请求的资源 Spring Boot Rest API 和 VUE 上不存在“Access-Control-Allow-Origin”标头

Posted

技术标签:

【中文标题】CORS 策略:请求的资源 Spring Boot Rest API 和 VUE 上不存在“Access-Control-Allow-Origin”标头【英文标题】:CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Spring Boot Rest API & VUE 【发布时间】:2020-05-19 14:52:01 【问题描述】:

从前端(用vue构建)向后端(用spring boot构建)发出请求时出现以下错误

Access to XMLHttpRequest at 'http://api.app.com/productorder/all' from origin 'http://my.app.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这是我的网络安全类:

@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter 
    private UserDetailsServiceImpl userDetailsService;
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Value("$cors.allowed-origins")
    private String allowedOrigins;

    public WebSecurity(UserDetailsServiceImpl userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) 
        this.userDetailsService = userDetailsService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    

    @Override
    protected void configure(HttpSecurity http) throws Exception 
        http.cors().and().csrf().disable().authorizeRequests()
                .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
                .antMatchers("/v2/**", "/configuration/**", "/swagger*/**", "/webjars/**")
                .permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                .addFilter(new JWTAuthorizationFilter(authenticationManager()))

                // this disables session creation on Spring Security
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception 
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    

  @Bean
  CorsConfigurationSource corsConfigurationSource() 
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration().applyPermitDefaultValues();

    config.setExposedHeaders(Arrays.asList("Access-Control-Allow-Headers", "Authorization, x-xsrf-token, Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, " +
            "Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"));

    // Move this into properties files
    // make sure to split the array before adding below
    config.setAllowedOrigins(Arrays.asList("http://localhost:3000","http://localhost:8080","http://my.app.com", "http://api.app.com"));
    config.setAllowedMethods(Arrays.asList("GET","POST", "UPDATE", "DELETE", "OPTIONS", "PUT"));

    source.registerCorsConfiguration("/**", config);
    return source;
  

【问题讨论】:

您可以在请求中添加标头吗? 【参考方案1】:

创建一个每个请求过滤器添加这个 response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH"); response.setHeader("Access-Control-Allow-Headers", "Date, Content-Type, Accept, X-Requested-With, Authorization, From, X-Auth-Token, Request-Id"); response.setHeader("Access-Control-Expose-Headers", "Set-Cookie"); response.setHeader("Access-Control-Allow-Credentials", "true");

【讨论】:

没有理由设置第二个过滤器。第一个过滤器应该足够了。【参考方案2】:

使用CorsConfiguration#setAllowedHeaders(List<String> allowedHeaders) (quote):

设置飞行前请求可以列为允许的标头列表 在实际请求期间使用。特殊值“*”允许实际 请求发送任何标头。

如果是以下之一,则不需要列出标题名称: Cache-Control、Content-Language、Expires、Last-Modified 或 Pragma。

默认情况下未设置。

例如在corsConfigurationSource()方法中添加:

config.setAllowedHeaders(Arrays.asList("Access-Control-Allow-Origin", "Authorization", "Accept", "Content-Type"));

请注意,如果不使用 Authorization,您可能不需要它,并且可能还需要添加其他标头。

【讨论】:

以上是关于CORS 策略:请求的资源 Spring Boot Rest API 和 VUE 上不存在“Access-Control-Allow-Origin”标头的主要内容,如果未能解决你的问题,请参考以下文章

在 java spring boot 中覆盖 CORS 策略

仅在特定条件下被 CORS 策略阻止的 Angular 请求

spring boot 2.4.0 版本中 CORS 策略的变化

CORS 策略错误 - 使用 Spring Boot + React 发现 api

Spring Boot文档阅读笔记-CORS Support

Spring Boot文档阅读笔记-CORS Support