AntiForgery令牌使用ASP.NET5 Web API而不使用NET46上的System.Web.Helpers

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

我找到的所有文章都来自this article并使用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;
}

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

其他来源ASP.NET5 AntiForgery Source Code

解决方法

在Controller处生成

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;
        }
    }    
}

在View中生成

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

<body>
    @GetAntixsrftoken()
</body>

验证

var antiForgery = Context.RequestServices.GetService<AntiForgery>();
antiForgery.Validate(Context,new AntiForgeryTokenSet(formToken,cookietoken));

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....