在ASP.NET Core

时间:2017-01-05 16:08:26

标签: asp.net-core asp.net-core-mvc .net-core coreclr

我想在ASP.NET Core应用程序中验证AntiForgery令牌。我知道我可以通过在SO帖子here

中建议的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>();
    }
}

1 个答案:

答案 0 :(得分:0)

我必须注入RecyclerView作为服务

Antiforgery

在startup.cs中添加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);
    }
}

使用我的middlware

   public void ConfigureServices(IServiceCollection services)
   {       
        services.AddAntiforgery();
   }