以编程方式生成请求验证令牌

时间:2020-07-05 19:29:47

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

从一个空的MVC项目开始,这是我的Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace AntiForgeryExample
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }
                
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseDeveloperExceptionPage();

            app.UseStatusCodePages();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });
        }
    }
}

这是我的HomeController.cs

using Microsoft.AspNetCore.Mvc;
using System.Net;

namespace AntiForgeryExample
{
    public class XyzController : Controller
    {
        [HttpPost]
        [ValidateAntiForgeryToken]
        public string Fgh() => "fgh 1";

        [HttpGet]
        public ContentResult Efg()
        {
            return new ContentResult()
            {
                ContentType = "text/html",
                StatusCode = (int)HttpStatusCode.OK,
                Content = @"<!DOCTYPE html>

                    <html>
                        <body>
                            <form method=""post"" action=""/Xyz/Fgh"">
                                <button type=""submit"">123</Button>
                            </form>                            
                        </body>
                    </html>"
            };
        }
    }
}

Startup.cs中的以下行添加了防伪中间件:

services.AddMvc();

因此,如果我们转到http://localhost:52838/Xyz/Efg,我们将获得一个带有单个按钮的简单页面:

enter image description here

如果按下按钮,我们将收到400个“错误请求”响应:

enter image description here

我认为这是因为我们尚未在帖子中传递有效的请求验证令牌。 Fgh方法应用了ValidateAntiForgeryToken属性:

[HttpPost]
[ValidateAntiForgeryToken]
public string Fgh() => "fgh 1";

因此,调用此方法时需要令牌。

this page所述,如果将form标签帮助程序与ASP.NET Core MVC或Razor Page一起使用,通常会自动包含此令牌的代码。它看起来像这样,并被包含在form标签中:

<input name="__RequestVerificationToken" type="hidden" value="CfDJ8NrAkS ... s2-m9Yw">

在上面显示的示例程序中,我们正在以编程方式生成带有表单的HTML。

我的问题是,有没有一种方法可以以编程方式从C#生成所需的令牌,而不必使用MVC视图或Razor页面。想法是,我们将获得令牌值,然后包含input标签:

<input name="__RequestVerificationToken" type="hidden" value="TOKEN VALUE HERE">

1 个答案:

答案 0 :(得分:1)

我在/r/dotnet subreddit上分享了这个问题。

/u/kenos1在此处提供了very helpful answer

您可以注入Microsoft.AspNetCore.Antiforgery.IAntiforgery并对其调用GetTokens()。

以下是文档:link

正如他在此处提到的,我们在IAntiforgery构造函数中注入了XyzController

private IAntiforgery antiforgery;

public XyzController(IAntiforgery antiforgery_)
{
    antiforgery = antiforgery_;
}

我们在注入的GetAndStoreTokens实例上调用IAntiforgery

var token_set = antiforgery.GetAndStoreTokens(HttpContext);

最后,我们在生成的HTML中使用结果标记:

return new ContentResult()
{
    ContentType = "text/html",
    StatusCode = (int)HttpStatusCode.OK,
    Content = string.Format(@"<!DOCTYPE html>

        <html>
            <body>
                <form method=""post"" action=""/Xyz/Fgh"">
                    <button type=""submit"">123</Button>

                    <input name=""__RequestVerificationToken"" type=""hidden"" value=""{0}"">
                </form>                            
            </body>
        </html>",
        
        token_set.RequestToken)
};

这是完整的控制器文件:

using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System.Net;

namespace AntiForgeryExample
{
    public class XyzController : Controller
    {
        private IAntiforgery antiforgery;

        public XyzController(IAntiforgery antiforgery_)
        {
            antiforgery = antiforgery_;
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public string Fgh() => "fgh 1";

        [HttpGet]
        public ContentResult Efg()
        {
            var token_set = antiforgery.GetAndStoreTokens(HttpContext);
                                                
            return new ContentResult()
            {
                ContentType = "text/html",
                StatusCode = (int)HttpStatusCode.OK,
                Content = string.Format(@"<!DOCTYPE html>

                    <html>
                        <body>
                            <form method=""post"" action=""/Xyz/Fgh"">
                                <button type=""submit"">123</Button>

                                <input name=""__RequestVerificationToken"" type=""hidden"" value=""{0}"">
                            </form>                            
                        </body>
                    </html>",
                    
                    token_set.RequestToken)
            };
        }
    }
}

ASP.NET Core 3.1官方文档提到了GetAndStoreTokens方法here