【问题标题】:Not able to set 'Access-Control-Allow-Origin' header in the response provided by Spring Boot Application无法在 Spring Boot 应用程序提供的响应中设置“Access-Control-Allow-Origin”标头
【发布时间】:2019-01-14 13:59:27
【问题描述】:

请阅读问题。我在 Stack Overflow 上尝试了所有答案。

错误:

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'. 
Origin 'http://localhost:4200' is therefore not allowed access. The 
credentials mode of requests initiated by the XMLHttpRequest is controlled by 
the withCredentials attribute.

在 Angular 的 4200 端口上运行的前端:

let headers = new Headers({
"Content-Type": "application/x-www-form-urlencoded"});
let options = new RequestOptions({ headers: headers ,withCredentials:true});

//body contains username and password.
this.http.post('http://localhost:8080/login',{body}, options).
subscribe(response => {
    console.log(response)    
});

后端使用 Spring Boot 在端口 8080 上运行:

@CrossOrigin(origins = "http://localhost:4200",allowCredentials="true")
@RestController
public class SecurityApplication {
...  //Rest Api's
}
//Security Config
protected void configure(HttpSecurity http) throws Exception {
    http.
        cors().and().httpBasic().and().formLogin()
        .and()
        .authorizeRequests()
            .antMatchers( "/", "/home", "/login").permitAll()
            .anyRequest().authenticated();
}

我正在点击 Spring Security 提供的 /login api。

我提到了https://www.concretepage.com/spring-4/spring-4-rest-cors-integration-using-crossorigin-annotation-xml-filter-example,据此 origins = "http://localhost:4200" 应在响应标头中设置 Access-Control-Allow-Origin 以提供给它的值,但我仍然得到通配符'*'作为响应。

我尝试了 corsFilters 但没有奏效。我在 Chrome 浏览器中启用了 CORS 扩展。我想知道为什么它没有将 Access-Control-Allow-Origin 设置为我提供的值以及如何解决它。

【问题讨论】:

  • 你有没有CorsConfigurationSource 暴露?
  • 是的,我通过引用 link 尝试过,但没有成功。

标签: angular spring-boot spring-security


【解决方案1】:

一种方法是不设置 Cross Origin。相反,在您的 Angular 应用程序中,创建一个代理文件 proxy.conf.json 并在启动您的 Angular 时使用

ng serve --proxy-conf proxy.conf.json

你的 proxy.conf.json 的内容将是:

{
    "/api": {
        "target": "http://localhost:8080/api",
        "secure": false,
        "changeOrigin": "true",
        "pathRewrite": {
            "^/api": ""
        } 
    }
}

最后在你的spring boot应用程序的application.properties中你可以设置:

server.context-path=/api

您对 api 的所有请求都将通过 api 上下文路径到达您的 Spring Boot 应用程序,并且不会出现跨源错误。

您对 Angular 的调用将是:

this.http.post('/api/login',{body}, options).subscribe(response => {
    console.log(response)    
});

【讨论】:

猜你喜欢
  • 2018-01-24
  • 2021-09-02
  • 2021-12-16
  • 1970-01-01
  • 2018-06-21
  • 2020-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多