您好我有以下应用:
前端在Angular 2中运行 localhost:4200
后备在Spring上运行 localhost:8080
我正在使用 Spring Security 。在服务器站点上,我有 CORSFilter :
response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
response.addHeader("Access-Control-Allow-Credentials", "true");
filterChain.doFilter(request, response);
以下是客户端网站:
private static headers: Headers = new Headers({ 'Content-Type': 'application/json' });
private static postOptions: RequestOptions = new RequestOptions({ headers: SecureHttpService.headers });
private static getOptions: RequestOptions = new RequestOptions({});
constructor(private http: Http) {
SecureHttpService.postOptions.withCredentials = true;
SecureHttpService.getOptions.withCredentials = true;
}
public get(url: string): Observable<Response> {
return this.http.get(url, SecureHttpService.getOptions);
}
public post(url: string, data: any): Observable<Response> {
return this.http.post(url, data, SecureHttpService.postOptions);
}
如您所见,我设置 withCredentials = true;
这是我的问题:
答案 0 :(得分:0)
这是我的解决方案:
根据阅读这篇精彩的article,预检请求的工作原理如下:
&#34;浏览器首先执行一个OPTIONS请求,其URL与目标请求相同,以检查它是否有权执行请求。此OPTIONS请求返回标识可以对URL执行的操作的标头。如果权限匹配,浏览器将执行请求。&#34;
所以我向Spring添加了过滤器,它将传递所有 OPTIONS 请求。
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String httpmethod = request.getMethod();
if(httpmethod.equals("OPTIONS")) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(request, response);
}
}
!请注意,我仅将此解决方案用于开发。