【发布时间】:2018-04-28 12:44:19
【问题描述】:
我的 Angular 客户端与后端分离,并且我在后端启用了 cors,一切正常,除了我的身份验证失败,因为 cookie 未添加到请求中。
在网上搜索后发现我应该在每个http请求上设置{withCredentials : true}。我设法在一个请求上做到了,它可以工作,但不是所有的请求。
我尝试使用 BrowserXhr How to send "Cookie" in request header for all the requests in Angular2?,但它不起作用,而且它也已被弃用 afaik。
我也尝试过 RequestOptions,但没有成功。
如何在每个 http 请求上设置 {withCredentials: true}?
稍后编辑:
@Injectable()
export class ConfigInterceptor implements HttpInterceptor {
constructor(private csrfService: CSRFService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let token = this.csrfService.getCSRF() as string;
const credentialsReq = req.clone({withCredentials : true, setHeaders: { "X-XSRF-TOKEN": token } });
return next.handle(credentialsReq);
}
}
【问题讨论】:
-
我添加了对 mea 有效的代码
-
见我的example
标签: angular http cookies oauth-2.0 cross-domain