在 Angular 文档中,提到了 Angularhttpclient
会自动发送cookie的值XSRF-TOKEN
在标题中X-XSRF-TOKEN
的帖子请求。文档链接 https://angular.io/guide/http#security-xsrf-protection
但它不会为我发送标头。这是我的代码
设置cookie的Nodejs代码
router.get('/set-csrf',function(req,res,next){
res.setHeader('Set-Cookie', "XSRF-TOKEN=abc;Path=/; HttpOnly; SameSite=Strict");
res.send();
})
我在 app.module.ts 中使用了 httpclient
imports: [
HttpClientModule
]
** 以上代码仅用于调试目的。我没有 set-csrf 端点。
但当我发送 post 请求时它不会发送任何标头。我无法调试。
我也将这个问题添加到了 Angular 的 github 存储库中。 HttpXsrfInterceptor 检查请求是 GET 还是 HEAD,或者是否以 http 开头。如果为 true,它将跳过添加标头。
这是代码HttpXsrfInterceptor 类 https://github.com/angular/angular/blob/54e02449549448ebab6f255f2da0b4396665c6f0/packages/common/http/src/xsrf.ts#L76
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const lcUrl = req.url.toLowerCase();
// Skip both non-mutating requests and absolute URLs.
// Non-mutating requests don't require a token, and absolute URLs require special handling
// anyway as the cookie set
// on our origin is not the same as the token expected by another origin.
if (req.method === 'GET' || req.method === 'HEAD' || lcUrl.startsWith('http://') ||
lcUrl.startsWith('https://')) {
return next.handle(req);
}
const token = this.tokenService.getToken();
// Be careful not to overwrite an existing header of the same name.
if (token !== null && !req.headers.has(this.headerName)) {
req = req.clone({headers: req.headers.set(this.headerName, token)});
}
return next.handle(req);
}
我不知道为什么他们跳过了 http/s 部分。这是我的github 中的问题 https://github.com/angular/angular/issues/18859