加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 06:39:02 所属栏目:asp.Net 来源:网络整理
导读:尝试在ASP.NET5(aka vNext)API上实现AntiForgery 我找到的所有文章都来自this article并使用System.Web.Helpers.AntiForgery.GetTokens,这不应该是ASP.NET5的方式 private static string GetTokenHeaderValue() { string cookieToken,formToken; System.Web.
尝试在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));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读