配置 ASP.Net Core Antiforgery 以与 Angular SPA 配合使用

问题描述 投票:0回答:2

如何配置 ASP.Net Core Web 应用程序以向 Angular 应用程序提供防伪令牌?

c# angular asp.net-core
2个回答
3
投票

我花了相当多的时间尝试将其拼凑在一起,因此我尝试帮助其他人尝试弄清楚如何使用 ASP.Net Core 6 和 Angular 来获取防伪令牌。

首先,Angular 开箱即用地处理通过每个 POST 请求将身份验证令牌传递到服务器 API。除了确保应用程序首次连接到服务器时将名为

XSRF-TOKEN
的 cookie 发送到客户端之外,您不需要做任何事情。所有配置都将在您的 ASP.Net Core Web 应用程序中

在您的 API 应用程序中,您需要进行一些设置才能实现这一点。打开您的

Program.cs
文件并将防伪服务添加到应用程序中:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAntiforgery(options =>
{
    options.HeaderName = "X-XSRF-TOKEN";
});

防伪服务负责创建令牌并帮助您验证从客户端返回的令牌是否有效。

现在您已经设置了服务,您需要生成 cookie 并将其发送到客户端。为此,我们需要设置请求-响应中间件,以便在客户端请求应用程序的起始点时发送 cookie。如果您的 Angular 应用程序和 API 都托管在同一网站上,或者如果您的 Angular 应用程序托管在另一个网站上,则可能会请求 default.html 页面,调用不受保护的端点(如

/api/Login
)来获取饼干。

var app = builder.Build();
app.MapControllers();

var service = app.Services.GetRequiredService<IAntiforgery>();

app.Use(async (context, next) =>
{
    var path = context.Request.Path;
    if (path.Equals("/default.html", StringComparison.CurrentCultureIgnoreCase))
    {
        // generate .AspNetCore.Antiforgery authentication cookie
        var tokenSet = service.GetAndStoreTokens(context);
    }

    await next(context);
});

此时,发送到客户端的唯一 cookie 是默认的

.AspNetCore.Antiforgery-something
,但 Angular 需要更多。我们需要更新请求-响应中间件,以便每当客户端请求应用程序的起点时也发送 XSRF-TOKEN cookie。

var app = builder.Build();
app.MapControllers();

var service = app.Services.GetRequiredService<IAntiforgery>();

app.Use(async (context, next) =>
{
    var path = context.Request.Path;
    if (path.Equals("/default.html", StringComparison.CurrentCultureIgnoreCase))
    {
        // generate .AspNetCore.Antiforgery authentication cookie
        var tokenSet = service.GetAndStoreTokens(context);
        var token = tokenSet.RequestToken;
        // duplicate the .AspNetCore.Antiforgery authentication and create a cookie called XSRF-TOKEN
        if (token != null)
        {
            context.Response.Cookies.Append("XSRF-TOKEN", token, new CookieOptions
            {
                Path = "/",
                HttpOnly = false
            });
        }
    }

    await next(context);
});

现在您将看到两个 cookie 被发送到 Angular 应用程序。需要这两个 cookie 才能正常工作。

.AspNetCore.Antiforgery-something
cookie 包含一个用于验证实际令牌的秘密。这称为双重提交 Cookie 方法(为 OzzyTheGiant 欢呼,从 https://stackoverflow.com/a/47054376/24856 获得有用的信息)。

现在所有管道都已设置完毕,将

[AutoValidateAntiforgeryToken]
属性添加到要保护的每个控制器的顶部。如果您想针对某些端点绕过此方法,请使用
[IgnoreAntiforgeryToken]
来修饰这些方法。

一切都准备好了。 Angular 应用程序将在第一个请求时获得两个 cookie,

XSRF-TOKEN
.AspNetCore.Antiforgery-something
。这些 cookie 将随每个请求发送回服务器。此外,Angular 将为每个
X-XSRF-TOKEN
请求添加一个名为
POST
的 HEADER 条目。防伪服务将在
[AutoValidateAntiforgeryToken]
逻辑中比较这些值,如果验证失败,则抛出期望。


-1
投票

如果我必须对 .Net 3.1 和 ReactJS 执行相同的操作怎么办? 我的 API 在 http://localhost:5661.api.myDomain.com 上提供服务 和在 http://localhost:3000.ui.myDomain.com 上运行的 React UI

© www.soinside.com 2019 - 2024. All rights reserved.