获取错误:“access control allow origin”标头包含多个值“*,*”,但只允许一个值

f87krz0w  于 2021-07-15  发布在  Java
关注(0)|答案(1)|浏览(688)

我尝试在java/spring中的Angular 前端和rest端点之间建立连接(我没有开发,也不太了解)。顺便说一句,一切正常。通过邮递,我在终端机里收到了信息
已被cors策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许来源”标头。
在dev instruments的network选项卡中,options方法出现错误403

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

所以,我在互联网上搜索了几次后发现了这种情况,原因是cors设置:通常,在这种情况下,一个选项调用在post之前发送;但是,由于cors的原因,期权认购是不允许的。所以,我试着在我的控制器上设置这一行

@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.

因此,根据post cors问题-请求的资源上不存在“access control allow origin”头,我尝试了以下解决方案:

@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”标头包含多个值“”,但只允许一个值。
所以,这是我达到的最后一点。如何解决关于多个值的最后一个错误?每次我处理这个问题时,我都会提前一步,错误会发生变化,但它仍然存在。

abithluo

abithluo1#

只需将此添加到您的Web安全配置适配器

@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 security:

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

相关问题