【问题标题】:XSRF-TOKEN not added to cookies by Angular (Client side) when .NET core API returns a response with an XSRF-TOKEN当 .NET 核心 API 返回带有 XSRF-TOKEN 的响应时,Angular(客户端)未将 XSRF-TOKEN 添加到 cookie
【发布时间】:2020-11-15 19:33:23
【问题描述】:

我正在使用 Angular10 和 .NET core 2.2。我已将 Startup.cs 配置为返回带有 XSRF-TOKEN 的响应。后端正在返回它,但 Angular 不会将它传递给浏览器的 cookie。

参考微软文档https://docs.microsoft.com/en-us/aspnet/core/security/anti-request-forgery?view=aspnetcore-3.1#javascript-ajax-and-spas

服务器端代码

  // on ConfigureServices
     services.AddAntiforgery(options =>
        {
            options.HeaderName = "X-XSRF-TOKEN";
        });

// on Configure

app.Use(next => context =>
        {
            string path = context.Request.Path.Value;
            if (path != null && path.ToLower().Contains("/api"))
            {
                var tokens = antiforgery.GetAndStoreTokens(context);

                context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
                new CookieOptions() { HttpOnly = false });
            }

            return next(context);
        });

【问题讨论】:

标签: c# .net angular .net-core


【解决方案1】:

在我的例子中,Angular 没有添加 XSRF-TOKEN cookie,因为我为客户端和 API 使用了不同的域。

要根据@David 评论解决此问题,我必须将withCredentials: true 添加到我的请求中

例如:

this._http.get<Array<string>>(`${environment.config.auth.BASE_API_URL}/Product/GetFeature`, { headers, withCredentials: true});

如果您为客户端 Angular 和服务器(在我的情况下为 asp.net 核心)使用单个相同的域托管,那么您不需要在客户端添加任何配置,仅在默认 cookie 名称应为“XSRF”的情况下-TOKEN”,头名应该是“X-XSRF-TOKEN”。

【讨论】:

    猜你喜欢
    • 2018-11-01
    • 2017-11-23
    • 2015-01-18
    • 2013-03-04
    • 2021-04-05
    • 2019-02-19
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多