[翻译]  How would I write an ActionFilter that ensures AntiForgeryTokens are used for every Post operation?

[CHINESE]  我如何编写一个ActionFilter来确保AntiForgeryTokens用于每个Post操作?


I want to use AntiForgeryTokens on every HttpPost Action using an ActionFilter that is in a controller named ControllerBase that every other controller inherits from.

我想在每个HttpPost Action上使用一个ActionFilter来使用AntiForgeryTokens,该ActionFilter位于每个其他控制器继承的名为ControllerBase的控制器中。

I want to do this by creating an ActionFilter that inherits from ValidateAntiForgeryToken which takes an argument that tells it what HTTP verbs to apply itself to. I then want to apply that filter on ControllerBase to ensure that the AntiForgeryToken is checked for EVERY POST operation on the entire site.

我想通过创建一个继承自ValidateAntiForgeryToken的ActionFilter来做到这一点,该ActionFilter接受一个参数,告诉它要将自身应用的HTTP动词。然后,我想在ControllerBase上应用该过滤器,以确保在整个站点上检查AntiForgeryToken是否进行了每次POST操作。

I was looking into using this solution, but

我正在考虑使用这个解决方案,但是

  • AuthorizationContext Constructor (ControllerContext) is an obsolete constructor involved and I am not sure how to rebuild the code using the recommended AuthorizationContext(ControllerContext controllerContext, ActionDescriptor actionDescriptor).

    AuthorizationContext构造函数(ControllerContext)是一个过时的构造函数,我不知道如何使用推荐的AuthorizationContext(ControllerContext controllerContext,ActionDescriptor actionDescriptor)重建代码。

  • It does not appear to use the AntiForgeryToken by default as I get the following error: A required anti-forgery token was not supplied or was invalid after every post action.

    默认情况下它似乎不使用AntiForgeryToken,因为我收到以下错误:未提供所需的防伪标记或在每个帖子操作后无效。

How should I rewrite my ActionFilter to meet current non-obsolete standards and to properly use an anti-forgery token on every [HttpPost] verb?

我应该如何重写ActionFilter以满足当前的非过时标准,并在每个[HttpPost]动词上正确使用防伪标记?

Do I have to include an anti-forgery token in every form myself (I am thinking I do)? (as opposed to it being automatically generated - don't laugh, I'm curious) Update: As pointed out in the comments; Yes, this has to be done with every form.

我是否必须在每种形式中都包含一个防伪标记(我在想)? (而不是自动生成 - 不要笑,我很好奇)更新:正如评论中指出的那样;是的,这必须在每个表格中完成。

Here is the code from my ControllerBase for reference:

以下是我的ControllerBase中的代码供参考:

[UseAntiForgeryTokenOnPostByDefault]
public class ControllerBase : Controller 
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class BypassAntiForgeryTokenAttribute : ActionFilterAttribute
    {
    }

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
    public class UseAntiForgeryTokenOnPostByDefault : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (ShouldValidateAntiForgeryTokenManually(filterContext))
            {
                var authorizationContext = new AuthorizationContext(filterContext.Controller.ControllerContext);

                //Use the authorization of the anti forgery token, 
                //which can't be inhereted from because it is sealed
                new ValidateAntiForgeryTokenAttribute().OnAuthorization(authorizationContext);
            }

            base.OnActionExecuting(filterContext);
        }

        /// <summary>
        /// We should validate the anti forgery token manually if the following criteria are met:
        /// 1. The http method must be POST
        /// 2. There is not an existing [ValidateAntiForgeryToken] attribute on the action
        /// 3. There is no [BypassAntiForgeryToken] attribute on the action
        /// </summary>
        private static bool ShouldValidateAntiForgeryTokenManually(ActionExecutingContext filterContext)
        {
            var httpMethod = filterContext.HttpContext.Request.HttpMethod;

            //1. The http method must be POST
            if (httpMethod != "POST") return false;

            // 2. There is not an existing anti forgery token attribute on the action
            var antiForgeryAttributes =
                filterContext.ActionDescriptor.GetCustomAttributes(typeof (ValidateAntiForgeryTokenAttribute), false);

            if (antiForgeryAttributes.Length > 0) return false;

            // 3. There is no [BypassAntiForgeryToken] attribute on the action
            var ignoreAntiForgeryAttributes =
                filterContext.ActionDescriptor.GetCustomAttributes(typeof (BypassAntiForgeryTokenAttribute), false);

            if (ignoreAntiForgeryAttributes.Length > 0) return false;

            return true;
        }
    }
}

2 个解决方案

#1


1  

You don't need to instantiate any AuthorizationContext or call the OnAuthorization method, simply:

您不需要实例化任何AuthorizationContext或调用OnAuthorization方法,只需:

if (ShouldValidateAntiForgeryTokenManually(filterContext))
{
    AntiForgery.Validate(filterContext.HttpContext, null);
}

#2


7  

I've used the following approach:

我使用了以下方法:

public class SkipCSRFCheckAttribute : Attribute
{
}

public class AntiForgeryTokenFilter : IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        if (IsHttpPostRequest(filterContext) && !SkipCsrfCheck(filterContext))
            AntiForgery.Validate();
    }

    private static bool IsHttpPostRequest(AuthorizationContext filterContext)
    {
        return filterContext.RequestContext.HttpContext.Request.HttpMethod == HttpMethod.Post.ToString();
    }

    private static bool SkipCsrfCheck(AuthorizationContext filterContext)
    {
        return filterContext.ActionDescriptor.GetCustomAttributes(typeof (SkipCSRFCheck), false).Any();
    }
}

Which enables us to disable it on a case-by-case basis using the SkipCSRFCheck attribute, and then registering it as a global filter in the Application_Start:

这使我们能够使用SkipCSRFCheck属性逐个禁用它,然后在Application_Start中将其注册为全局过滤器:

GlobalFilters.Filters.Add(new AntiForgeryTokenFilter());

GlobalFilters.Filters.Add(new AntiForgeryTokenFilter());


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号