【问题标题】:unable to find anti forgery token in filterContext无法在 filterContext 中找到防伪令牌
【发布时间】:2016-08-28 17:20:14
【问题描述】:

我指的是在我的 Web 应用程序中实现防伪的以下链接。

link

$.ajaxAntiForgery({
    type: "POST",            
    url: "sampleapp",
    contentType: false,
    processData: false,
    cache: false,
    success: function (result) {       }
});

令牌是按照文档中的描述创建的,但在代码隐藏中它会在下面的行中引发错误。

public abstract class BaseController : Controller
{
    private readonly ValidateAntiForgeryTokenAttribute _validator;
    private readonly AcceptVerbsAttribute _verbs;
    protected BaseController (HttpVerbs verbs)
    {
        this._verbs = new AcceptVerbsAttribute(verbs);
        this._validator = new ValidateAntiForgeryTokenAttribute();            
    }

    protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        string httpMethodOverride = filterContext.HttpContext.Request.GetHttpMethodOverride();
        if (this._verbs.Verbs.Contains(httpMethodOverride, StringComparer.OrdinalIgnoreCase))
        {
            this._validator.OnAuthorization(filterContext);
        }
    }
}

【问题讨论】:

    标签: c# asp.net-mvc antiforgerytoken


    【解决方案1】:

    尝试改用这个。

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class ValidateTokenAttribute : FilterAttribute, IAuthorizationFilter
    {
        public string VariableTokenKey = "__RequestVerificationToken";
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            try
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest()) { this.ValidateRequestHeader(filterContext.HttpContext.Request); }
                else { AntiForgery.Validate(); }
            }
            catch
            {
                InvalidRequest(filterContext, "103", "", "Token not found.");
            }
        }
        private void ValidateRequestHeader(HttpRequestBase request)
        {
            string cookieToken = string.Empty;
            string formToken = string.Empty;
            string tokenValue = request.Headers[this.VariableTokenKey]; // read the header key and validate the tokens.
            if (!string.IsNullOrEmpty(tokenValue))
            {
                var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];
                cookieToken = antiForgeryCookie != null ? antiForgeryCookie.Value : null;
            }
            AntiForgery.Validate(cookieToken, tokenValue); // this validates the request token.
        }
        private void InvalidRequest(AuthorizationContext filterContext, string errorCode, string sMessage, string eMessage)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult
                {
                    Data = new { ErrorCode = errorCode, Message = eMessage },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                ViewDataDictionary viewData = new ViewDataDictionary();
                viewData.Add("ShortMessage", "Access denied.");
                viewData.Add("Message", "Anti forgery token not found.");
                filterContext.Result = new ViewResult { MasterName = "", ViewName = "Error", ViewData = viewData };
            }
        }
    }
    

    【讨论】:

    • 你能帮我理解我发布的代码有什么问题吗?
    • @Ammu - 您发布的代码不足以让参考告诉您出了什么问题。如果你能让我知道整个班级,那么我可以建议哪个部分受到了损害。我能够根据您的推荐链接成功构建和运行。
    • 我已经更新了整个代码。如果需要任何更改,请告诉我。
    猜你喜欢
    • 2017-07-21
    • 2021-06-09
    • 2023-03-30
    • 1970-01-01
    • 2016-05-07
    • 1970-01-01
    • 2020-03-09
    • 2016-03-23
    相关资源
    最近更新 更多