【问题标题】:CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Spring Boot Rest API & VUECORS 策略:请求的资源 Spring Boot Rest API 和 VUE 上不存在“Access-Control-Allow-Origin”标头
【发布时间】: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;
  }
}

【问题讨论】:

  • 您可以在请求中添加标头吗?

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


【解决方案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,您可能不需要它,并且可能还需要添加其他标头。

【讨论】:

    猜你喜欢
    • 2021-09-29
    • 2017-09-10
    • 2017-10-08
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    • 2021-12-27
    • 1970-01-01
    相关资源
    最近更新 更多