简体   繁体   English

CORS 策略:请求的资源上不存在“访问控制允许来源”header Spring 引导 Rest API & VUE

[英]CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Spring Boot Rest API & VUE

I have been getting the following errors when making requests from the frontend(built with vue) to the backend(built with spring boot)从前端(使用 vue 构建)向后端(使用 spring 引导构建)发出请求时出现以下错误

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.

Here is my WebSecurity Class:这是我的 WebSecurity Class:

@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;
  }
}

Create a Once per request filter add this 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");创建一个每个请求过滤器一次添加此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"); 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");

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

Set the list of headers that a pre-flight request can list as allowed for use during an actual request.将飞行前请求可以列出的标头列表设置为允许在实际请求期间使用。 The special value "*" allows actual requests to send any header.特殊值“*”允许实际请求发送任何 header。

A header name is not required to be listed if it is one of: Cache-Control, Content-Language, Expires, Last-Modified, or Pragma.如果 header 名称是以下之一,则无需列出:Cache-Control、Content-Language、Expires、Last-Modified 或 Pragma。

By default this is not set.默认情况下未设置。

For example, add in the corsConfigurationSource() method:例如,在corsConfigurationSource()方法中添加:

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

Notice that you may not need Authorization if it isn't used and may need to add other headers as well.请注意,如果不使用授权,您可能不需要Authorization ,并且可能还需要添加其他标头。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 CORS 策略:请求的资源 Spring Boot Rest API 上不存在“Access-Control-Allow-Origin”标头 - CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Spring Boot Rest API CORS Spring Security 配置 - 404 请求的资源上不存在“Access-Control-Allow-Origin”标头 - CORS Spring Security configuration - 404 No 'Access-Control-Allow-Origin' header is present on the requested resource 不存在“Access-Control-Allow-Origin”header (CORS) - Spring Boot (Spring security) 微服务 + Vue.js - No 'Access-Control-Allow-Origin' header is present (CORS) - Spring Boot (Spring security) Microservices + Vue.js Spring 启动 OAuth 客户端配置给出“No 'Access-Control-Allow-Origin' header 存在于请求的资源上。” - Spring boot OAuth Client config giving "No 'Access-Control-Allow-Origin' header is present on the requested resource." <spring boot>请求的资源上不存在“Access-Control-Allow-Origin”header</spring> - <Spring Boot> No 'Access-Control-Allow-Origin' header is present on the requested resource angular 9 和 spring 启动 2 中请求的资源上不存在“访问控制允许来源”header - No 'Access-Control-Allow-Origin' header is present on the requested resource in angular 9 and spring boot 2 'http://localhost:4200' 已被 CORS 策略阻止:请求的资源上不存在'Access-Control-Allow-Origin' header - 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource 被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”header。 Java 带有 CrossOrigin("*") 注释的后端 - Blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Java Backend with CrossOrigin("*") annotation Angular 和 Spring Boot:请求的资源上不存在“Access-Control-Allow-Origin”标头。 如何通过angular和spring boot解决 - Angular and Spring boot: No 'Access-Control-Allow-Origin' header is present on the requested resource. How to solve it by angular and spring boot 尽管存在请求的资源,但没有“ Access-Control-Allow-Origin”标头存在 - No 'Access-Control-Allow-Origin' header is present on the requested resource despite it is there
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM