【问题标题】:Validating AntiForgery token globally in ASP.NET Core在 ASP.NET Core 中全局验证 AntiForgery 令牌
【发布时间】:2017-05-20 06:20:45
【问题描述】:

我想在 ASP.NET Core 应用程序中验证 AntiForgery 令牌。我知道我可以按照 SO post 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>();
    }
}

【问题讨论】:

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


    【解决方案1】:

    我必须注入 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 中添加 Antiforgery 作为服务

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

    使用我的中间件

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

    【讨论】:

      猜你喜欢
      • 2020-08-22
      • 2020-09-04
      • 2019-11-19
      • 2020-07-01
      • 2021-12-17
      • 1970-01-01
      • 2015-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多