无法在Spring Boot Application提供的响应中设置'Access-Control-Allow-Origin'标头

时间:2018-08-07 12:59:19

标签: angular spring-boot spring-security

请阅读问题。我尝试了所有关于堆栈溢出的答案。

错误:

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 设置为我提供的值以及如何解决该问题。

1 个答案:

答案 0 :(得分:0)

一种方法是不设置交叉原点。相反,在您的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)    
});