c# - 在 MVC 应用程序上自动执行防伪 token 验证

标签 c# asp.net-mvc asp.net-identity

有没有一种方法可以在 Controller 上的所有 HTTP post 方法上自动添加 [ValidateAntiForgeryToken] 注释,而无需显式定义它?

还有没有一种方法可以扩展 MVC Html.BeginForm() 帮助程序以始终包含防伪标记?

最后这样做的目的是保持整个应用程序的一致性,在某些情况下是否有理由不这样做?

最佳答案

我自己正在研究这个主题并在下面编译了完整的解决方案,还有 here .它由几个部分组成,包括 AntiForgeryTokenFilterProviderBeginSecureForm 辅助方法。它还允许使用 DisableAntiForgeryCheckAttribute 跳过单个操作的验证。

public class AntiForgeryTokenFilterProvider : IFilterProvider
{
    public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        IEnumerable<FilterAttribute> filters = actionDescriptor.GetFilterAttributes(true);

        bool disableAntiForgery = filters.Any(f => f is DisableAntiForgeryCheckAttribute);

        string method = controllerContext.HttpContext.Request.HttpMethod;

        if (!disableAntiForgery
            && String.Equals(method, "POST", StringComparison.OrdinalIgnoreCase))
        {
            yield return new Filter(new ValidateAntiForgeryTokenAttribute(), FilterScope.Global, null);
        }
    }
}

[AttributeUsage(AttributeTargets.Method)]
public sealed class DisableAntiForgeryCheckAttribute : FilterAttribute
{
}

// Usage:
public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        //**//
        FilterProviders.Providers.Add(new AntiForgeryTokenFilterProvider());
        //**//
    }
}

// Html Helper method
public static class HtmlExtensions
{
    public static MvcForm BeginSecureForm(this HtmlHelper html, string action, string controller)
    {
        var form = html.BeginForm(action, controller);
        html.ViewContext.Writer.Write(html.AntiForgeryToken().ToHtmlString());

        return form;
    }
}

关于c# - 在 MVC 应用程序上自动执行防伪 token 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30585872/

相关文章:

c# - 如果发生任何异常,如何使 Task.WaitAll() 中断?

Javascript Html.Checkbox onchange 事件

c# - EF 创建额外表

asp.net-mvc - 使用外部访问 token 或本地访问 token

c# - 无法使用 EFCore、EntityState.Modified : "Database operation expected to affect 1 row(s) but actually affected 0 row(s)." 编辑数据库条目

c# - System.Drawing 不存在?

c# - Visual Studio 2002 : C# freezes when sending file over TCP/IP

c# - 从用户控件内部向 tabcontrol 添加选项卡

html - 如何在源不存在的情况下显示默认图像

asp.net-mvc - 使用 data-val ="true"是正确的方法,强制进行所需的验证