仅针对特定操作忽略ValidateAntiForgeryToken [英] Ignore ValidateAntiForgeryToken only for specific action

查看:163
本文介绍了仅针对特定操作忽略ValidateAntiForgeryToken的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于安全原因,我更喜欢在baseController的顶部添加ValidateAntiForgeryToken属性,以便所有操作都会受到该属性的影响.

for security reasons, i prefer to add the attribute ValidateAntiForgeryToken on top of my baseController so all the actions will be affected from that attribute.

我只想对单个操作禁用该属性.

I would like to disable that attribute only for single action.

不为我的baseController派生不是一种选择. 不幸的是,ValidateAntiForgeryToken属性是密封类,因此我无法基于原始的ValidateAntiForgeryToken属性创建自己的customValidateAntiForgeryToken属性.

not deriving for my baseController is not an option. unfortunately, ValidateAntiForgeryToken atribute is sealed class so i can't create my own customValidateAntiForgeryToken attribute based on the original ValidateAntiForgeryToken one.

推荐答案

确实,ValidateAntiForgeryToken类是密封的,但并不是我们自己推出的火箭科学:

It's true that the ValidateAntiForgeryToken class is sealed but it's not rocket science to roll our own:

public class MyValidateAntiForgeryTokenAttribute: FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        System.Web.Helpers.AntiForgery.Validate();
    }
}

当然,在我们的实现中,剩下的就是从filterContext添加一些检查,检查当前动作是否用某些自定义的ExcludeFromAntiForgeryValidation属性修饰,而不调用Validate方法.

Now of course all that's left in our implementation is to add some check from the filterContext whether the current action is decorated with some custom ExcludeFromAntiForgeryValidation attribute and not call the Validate method.

类似的东西:

public class MyValidateAntiForgeryTokenAttribute: FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        bool shouldValidate = !filterContext
            .ActionDescriptor
            .GetCustomAttributes(typeof(ExcludeFromAntiForgeryValidationAttribute), true)
            .Any();
        if (shouldValidate)
        {
            System.Web.Helpers.AntiForgery.Validate();
        }
    }
}

然后编写一个自定义属性:

and then just write a custom attribute:

[AttributeUsage(AttributeTargets.Method)]
public class ExcludeFromAntiForgeryValidationAttribute : Attribute
{
}

您将用来装饰控制器操作的方式,要使用该操作来排除防伪验证:

that you would use to decorate your controller actions with for which you want to exclude antiforgery validation:

[HttpPost]
[ExcludeFromAntiForgeryValidation]
public ActionResult Index(MyViewModel model)
{
    ...
}

这篇关于仅针对特定操作忽略ValidateAntiForgeryToken的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆