使用Spring Boot和Vue.JS的Access-Control-Allow-Origin多个值

时间:2019-07-10 18:16:52

标签: spring spring-boot vue.js

我的API上有用于CORS的此类:

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

    @Configuration
    public class CorsConfiguration implements WebMvcConfigurer {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedMethods("*").allowedOrigins("*").allowedHeaders("*");

 }
}

请求返回200,这是我对前端的回答:

  

[日期:“星期三,2019年7月10日18:11:54 GMT”,服务器:“ Apache / 2.4.18   (Ubuntu)”,Vary:“授权”,Cache-Control:“无缓存,私有”,   X-Robots-Tag:“ noindex”,访问控制允许来源:“ *”,   访问控制允许方法:“ POST,GET,PUT,PATCH,DELETE,OPTIONS”,   访问控制允许标题:“授权,内容类型,接受”,   Access-Control-Allow-Credentials:“ true”,Keep-Alive:“ timeout = 5,   max = 100“,连接:”保持活动“,传输编码:”分块“,   内容类型:“ application / json”]

但是在Chrome控制台中,我看到了:

  

访问“ http://localhost:3000/api/v1/empresas”处的XMLHttpRequest   来自来源“ http://localhost:8080”的信息已被CORS政策阻止:   “ Access-Control-Allow-Origin”标头包含多个值“ *”,   *',但只允许一个。

我的控制器:

@GetMapping(value = "empresas", produces = "application/json;charset=UTF-8")
public ResponseEntity listaEmpresa(@NotNull @RequestHeader String authorization) throws IOException {
    tokenValidatorService.validaToken(authorization);
    return companyModel.listaEmpresas(authorization);
}

我该怎么办?我没有在我的代码中随时设置访问控制允许起源。

1 个答案:

答案 0 :(得分:1)

我通常使用这种配置,并且可以正常工作。

确保@Configuration类已在应用程序上下文中加载

@Configuration
public class CorsConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedHeaders("*")
                    .allowedMethods("*");
            }
        };
    }
}

如果您具有触发飞行前请求的安全机制,则还必须按如下所示对所有应用程序进行HttpMethod.OPTIONS调用

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class KsSecurity extends WebSecurityConfigurerAdapter {

    ...

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .antMatchers(HttpMethod.OPTIONS, "/**")    // <---------- You need this
                .antMatchers(
                        "/**/*.{js,html,css,ico}",
                        "/i18n/**",
                        "/assets/**",
                        "/v2/api-docs/**",
                        "/webjars/**",
                        "/swagger-resources/**",
                        "/swagger-ui.html");
    }

    ...

}