我需要指定 CORS 标头,因为我需要在每个请求中发送 cookie 密钥。我有一个后端,在不同的服务器上使用Java Spring Boot和带有Angular 5的UI。
在UI端,我使用下一个TS代码调用服务器:
@Injectable()
export class CoreApi {
private baseUrl = 'http://localhost:8080/rest/';
constructor(public http: HttpClient) {
}
public get(url: string = ''): Observable<any> {
return this.http.get(this.getUrl(url), { withCredentials: true });
}
public post(url: string, data: any = {}): Observable < any > {
return this.http.post(this.getUrl(url), data, { withCredentials: true });
}
private getUrl(url: string = ''): string {
return this.baseUrl + url;
}
}
我需要withCredentials: true
才能发送cookie
否则 Spring 安全性无法识别没有会话 ID 的用户。但是在服务器上,我response.setHeader("Access-Control-Allow-Origin", "*")
了UI和后端的两个不同服务器的可能性。
而我陷入了恶性循环:如果我删除Access-Control-Allow-Origin - *
我会得到:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
如果我删除withCredentials: true
则 Spring 安全性在没有会话 ID 的情况下无法正常工作。并且所有请求都在身份验证后 -UNAUTHORIZED
没有cookie。
我认为需要实施源白名单,并在涉及凭据时使用有效源响应 CORS 请求。但是这是怎么做到的呢? 如果您知道任何事情,请告诉我。谢谢!
可能是这样的过滤器:
@WebFilter(urlPatterns = {"/*" })
public class CorsRestFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
...somehow sfecifying Access-Control-Allow-Origin...
response.setHeader("Access-Control-Allow-Methods", "POST, GET");
chain.doFilter(req, res);
}
}
创建常量服务组件并将其注入服务方法调用中 前任:
服务.ts
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
withCredentials: true,
};
demoServiceMethod(requestparameter): Observable<PayloadResponse<any>> {
return this.http.post<PayloadResponse<any>>(environment.baseurl +
'v1/test/api', requestparameter, httpOptions)
.pipe(catchError(this.apiErrorService.handleError<PayloadResponse<any>>('operation name ')));
}
您还需要添加Access-Control-Allow-Origin
标头。
response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
如果使用凭据进行跨源调用,则需要添加显式主机,而不是*
。 否则,您的呼叫将被浏览器阻止。
-
如果您使用的是 spring,您也可以使用他们的crossorigin
标签: https://spring.io/guides/gs/rest-service-cors/