繁体   English   中英

出现错误:'Access-Control-Allow-Origin' header 包含多个值 '*, *',但只允许一个

[英]Getting error: 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed

I tried to make a connection between my Angular frontend and a REST Endpoint in Java / Spring (which I didn't developed and don't know so well). 通过 GET,一切正常。 通过 POST,我在终端收到消息

已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”header。

并且,在开发工具的“网络”选项卡中,OPTIONS 方法出现错误 403

Request Method: OPTIONS
Status Code: 403 
Remote Address: xx.xx.xx.xx:xxxx
Referrer Policy: strict-origin-when-cross-origin

所以,我在互联网上搜索了几次后发现了这种情况,原因是 CORS 设置:通常,在这种情况下,在 POST 之前发送 OPTIONS 调用; 但是,由于 CORS,不允许调用 OPTIONS。 所以,我试图在我的 controller 上设置这一行

@CrossOrigin(origins = "*", methods = {RequestMethod.OPTIONS, RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE})

这次错误改变了

Multiple CORS header 'Access-Control-Allow-Origin' not allowed
But the code I added is the only similar to @CrossOrigin, I dind't found others similar.

因此,根据帖子CORS 问题 - No 'Access-Control-Allow-Origin' header is present on the requested resource ,我尝试了以下解决方案:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
    }
}

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.csrf().disable();
        http.cors();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(ImmutableList.of("*"));
        configuration.setAllowedMethods(ImmutableList.of("HEAD",
                "GET", "POST", "PUT", "DELETE", "PATCH"));
        // setAllowCredentials(true) is important, otherwise:
        // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
        configuration.setAllowCredentials(true);
        // setAllowedHeaders is important! Without it, OPTIONS preflight request
        // will fail with 403 Invalid CORS request
        configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

但是这次我在控制台看到的错误变成了

已被 CORS 策略阻止:“Access-Control-Allow-Origin”header 包含多个值“*、*”,但只允许一个。

所以,这是我到达的最后一点。 如何解决关于多个值的最后一个错误? 每次我处理这个问题时,我都会提前一步,错误会发生变化,但它仍然存在。

只需将其添加到您的 WebSecurityConfigurerAdapter

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    
/*@Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
    }*/ not needed

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // by default uses a Bean by the name of corsConfigurationSource
            .cors(withDefaults())
            ...
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("https://localhost:5000"));// if your front end running on localhost:5000
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

确保您没有任何其他过滤器或注释 cors 除了上面的代码

Spring 安全文档中的 Spring CORS 部分

如果您不使用 Spring 安全性:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }


    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry
                .addMapping("/**")
                .allowedOrigins("*","http://localhost:5000");// list all domains
            }
        };
    }
}

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM