Angular 6 和 AutoValidateAntiforgeryToken

Angular 6 and AutoValidateAntiforgeryToken

我搜索了很多,但没有找到如何实现 AutoValidateAntiforgeryToken。
我正在使用 TypeScript 创建一个 Angular 6 spa,连接到端点 .NET Core 2.1
在 ConfigureServices 添加

services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

在 AddMvc() 之前 在配置中添加

app.Use(next => context =>
{
    string path = context.Request.Path.Value;
    if (string.Equals(path, "/", StringComparison.OrdinalIgnoreCase) || string.Equals(path, "/index.html", StringComparison.OrdinalIgnoreCase))
    {
        // We can send the request token as a JavaScript-readable cookie,
        // and Angular will use it by default.
        var tokens = antiforgery.GetAndStoreTokens(context);
        context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false });
    }
    return next(context);
});

Angular 文档不清楚,如果我理解得很好,我应该读取一个名为 X-XSRF-TOKEN 的 cookie 并在 http 调用中作为 header 传回:但我尝试读取angular 中的此 cookie(使用 ngx-cookie-service,代码为 this.cookieSvc.get("X-XSRF-TOKEN"))此 cookie 为空。
如果有人能帮忙,谢谢。

对于您的问题,请检查以下几点以更好地了解您的问题。

  1. 对于CookieXSRFStrategy,它将XSRF-TOKEN配置为cookie name,将X-XSRF-TOKEN配置为header Name对于XSRF
  2. 为了对应AngularAsp.Net Core像您一样使用这个约定。

    • 将您的应用配置为在名为 XSRF-TOKEN

    • 的 cookie 中提供令牌
    • 配置防伪服务以查找名为 X-XSRF-TOKEN 的 header。

因此,如果您想从 Angular 站点获取 AntiforgeryToken,请尝试通过 XSRF-TOKEN 查询 cookie。