繁体   English   中英

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

[英]Configure ASP.Net Core Antiforgery to work with Angular SPA

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

我花了相当多的时间试图把它拼凑起来,所以这是我试图帮助其他人试图弄清楚如何让防伪令牌与 ASP.Net Core 6 和 Angular 一起使用的尝试。

首先,开箱即用的 Angular 通过每个 POST 请求处理将身份验证令牌传递给服务器 API。 除了确保在应用程序首次连接到服务器时将名为XSRF-TOKEN的 cookie 发送到客户端之外,您不需要做任何事情。 所有配置都将在您的 ASP.Net Core Web 应用程序中

在您的 API 应用程序中,您需要做一些设置来实现这一点。 打开Program.cs文件并将 Antiforgery 服务添加到应用程序:

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

Antiforgery 服务负责创建令牌并帮助您验证从客户端收到的令牌是否有效。

现在您已经设置了服务,您需要生成 cookie 并将其发送到客户端。 为此,我们需要设置 Request-Response 中间件以在客户端请求应用程序的起点时发送 cookie。 That might be requesting the default.html page if your Angular application and API are both hosted on the same website, or, if your Angular application is hosted on another site, calling an endpoint that isn't protected (like /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 需要更多。 我们需要更新 Request-Response 中间件,以便在客户端请求应用程序起点时也发送 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);
});

现在您会看到两个 cookies 被发送到 Angular 应用程序。 需要这两个 cookies 才能工作。 .AspNetCore.Antiforgery-something cookie 包含一个秘密,用于根据实际令牌进行验证。 这称为双重提交 Cookie 方法(为来自https://stackoverflow.com/a/47054376/24856的有用信息,为OzzyTheGiant干杯)。

现在所有管道都已设置,将[AutoValidateAntiforgeryToken]属性添加到您要保护的每个 controller 的顶部。 如果您想为某些端点绕过这个,请使用[IgnoreAntiforgeryToken]来装饰这些方法。

你都准备好了。 Angular 应用程序将在第一个请求时获得两个 cookies XSRF-TOKEN.AspNetCore.Antiforgery-something 这些 cookies 将随每个请求发送回服务器。 此外,Angular 将为每个POST请求添加一个名为X-XSRF-TOKEN的 HEADER 条目。 Antiforgery 服务将在[AutoValidateAntiforgeryToken]逻辑中比较这些值,并在验证失败时抛出一个期望值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM