在 NET46 上使用 ASP.NET5 Web API 的防伪令牌,无需 System.Web.Helpers

cil*_*ler 5 asp.net asp.net-mvc antiforgerytoken asp.net-web-api owin

尝试在 ASP.NET5 (又名 vNext) API上实现 AntiForgery

我找到的所有文章均源自本文,并使用System.Web.Helpers.AntiForgery.GetTokens,这不应该是 ASP.NET5 的方式

private static string GetTokenHeaderValue() 
{
   string cookieToken, formToken;
   System.Web.Helpers.AntiForgery.GetTokens(null, out cookieToken, out formToken);
   return cookieToken + ":" + formToken;
}
Run Code Online (Sandbox Code Playgroud)

是否有任何实现实际上显示了如何在 ASP.NET5 中检索这些令牌

附加源ASP.NET5 AntiForgery 源代码

cil*_*ler 4

在控制器处生成

using Microsoft.AspNet.Mvc;
using Microsoft.Framework.DependencyInjection;

namespace MyApp.App.Controllers
{
    public class MyController : Controller
    {
        public string GetAntiForgeryTokens()
        {
            var antiForgery = Context.RequestServices.GetService<AntiForgery>();
            AntiForgeryTokenSet antiForgeryTokenSet = antiForgery.GetTokens(Context, null);
            string output = antiForgeryTokenSet.CookieToken + ":" + antiForgeryTokenSet.FormToken;
            return output;
        }
    }    
}
Run Code Online (Sandbox Code Playgroud)

在视图中生成

@inject AntiForgery antiForgery
@functions
{
    public string GetAntiForgeryTokens()
    {
        AntiForgeryTokenSet antiForgeryTokenSet = antiForgery.GetTokens(Context, null);
        string output = antiForgeryTokenSet.CookieToken + ":" + antiForgeryTokenSet.FormToken;
        return output;
    }
}

<body>
    @GetAntiXsrfToken()
</body>
Run Code Online (Sandbox Code Playgroud)

证实

var antiForgery = Context.RequestServices.GetService<AntiForgery>();
antiForgery.Validate(Context, new AntiForgeryTokenSet(formToken, cookieToken));
Run Code Online (Sandbox Code Playgroud)