在 ASP.NET Core 中全局验证 AntiForgery 令牌

Validating AntiForgery token globally in ASP.NET Core

我想在 ASP.NET 核心应用程序中验证 AntiForgery 令牌。我知道我可以按照 SO post

中的建议通过在 Action 方法上添加 [AutoValidateAntiforgeryToken][ValidateAntiforgeryToken] 属性来单独做到这一点

我正在寻找为所有 POST 方法验证令牌的全局方法。所以我创建了一个中间件来这样做。但是我找不到合适的方法来验证令牌。就像在经典 asp.net 中一样,有 AntiForgery.Validate()。 ASP.NET Core

中的等效方法是什么
public class ValidateAntiForgeryTokenMiddleware
{
    private readonly RequestDelegate _next;

    public ValidateAntiForgeryTokenMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        if (httpContext.Request.Method.ToUpper() == "POST")
        {
            // where does this mehod exists?
            // i could not find it in Microsoft.AspNetCore.Antiforgery namespace
            AntiForgery.Validate();
        }

        await _next(httpContext);
    }
}

public static class ValidateAntiForgeryTokenMiddlewareExtensions
{
    public static IApplicationBuilder UseValidateAntiForgeryToken(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<ValidateAntiForgeryTokenMiddleware>();
    }
}

我必须将 Antiforgery 作为服务注入

public class ValidateAntiForgeryTokenMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IAntiforgery _antiforgery;

    public ValidateAntiForgeryTokenMiddleware(RequestDelegate next, IAntiforgery antiforgery)
    {
        _next = next;
        _antiforgery = antiforgery;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        if (httpContext.Request.Method.ToUpper() == "POST")
        {
            await _antiforgery.ValidateRequestAsync(httpContext);
        }

        await _next(httpContext);
    }
}

在 startup.cs

中添加防伪作为服务
   public void ConfigureServices(IServiceCollection services)
   {       
        services.AddAntiforgery();
   }

使用我的中间件

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
    {
        app.UseValidateAntiForgeryToken();

   }