【发布时间】:2025-12-26 18:05:16
【问题描述】:
在 Angular 文档中,提到了 Angular httpclient 会在 post 请求的标头 X-XSRF-TOKEN 中自动发送 cookie XSRF-TOKEN 的值。 Documentation link
但它不会为我发送标题。这是我的代码
设置 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 class中的代码
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 部分。这是我的issue in github
【问题讨论】:
-
你使用 CORS 请求吗?
-
我正在添加标题
"Access-Control-Allow-Headers","*" -
我看到了你的问题。在我看来,角度应该以不同的方式处理 http[s] 链接。例如,分别存储每个域的最后一个 csrf 令牌。让另一个拦截器绞盘以这种方式处理 csrf 是否很好?
-
我不明白的一件事(我在github问题中也提到过)为什么http url需要特殊处理?因为 owasp 指南和*文章都没有提到任何此类情况。你提到为每个域存储 csrf 令牌,你能解释一下这个 http/https 和多个域吗?我猜这仅适用于多域场景(子域),但它与以 http/https 开头的 url 有什么关系?
-
我的意思是,如果 url 以 http/https Angular 应用程序调用后端在不同的资源上,加载的 Angular 应用程序不同。它可以是子域场景,甚至可以是允许 CORS 访问的完全不同的站点。因此,如果它是不同的域,他们每个人都不能互相认识,并且他们分别发送 csrf 令牌。因此,如果 Angular 应用程序看到 url 以 http 开头,则不应发送从不以 http 开头的 url 获得的 csrf 令牌,因为它可能导致泄露令牌。而不是这个应用程序应该跟踪由域分割的 csrf 令牌,并将令牌发送到从中获取它的域。
标签: angular cookies csrf-protection x-xsrf-token