【问题标题】:Automatically add anti-forgery tokens in ASP.NET MVC with Razor使用 Razor 在 ASP.NET MVC 中自动添加防伪令牌
【发布时间】:2018-03-31 11:06:24
【问题描述】:
为防止跨站请求伪造,您需要为每个表单添加防伪令牌。
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
}
我想避免在所有表单中添加@Html.AntiForgeryToken。有没有办法自动化这个过程?
德国人Wikipedia article (Image) 声明在@Html.BeginForm 之后会自动添加一个带有令牌的隐藏字段,但看起来这不正确。
【问题讨论】:
标签:
asp.net-mvc
security
razor
antiforgerytoken
【解决方案1】:
找到了一个(非最优)解决方案here。
他使用另一种扩展方法来添加防伪令牌。这样做的缺点是您需要为所有现有 HtmlHelper 扩展提供新方法,并且代码可能会变得不一致。
public static class FormExtensions
{
public static MvcForm BeginDataForm(this HtmlHelper html, string action, string controller)
{
var form = html.BeginForm(action, controller);
html.ViewContext.Writer.Write(html.AntiForgeryToken().ToHtmlString());
return form;
}
}
在服务器端,他找到了一个优雅的解决方案来验证令牌。他添加了一个新的 AuthorizationFilter 并在每个 Post Method 上验证令牌。
public class GlobalAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
public sub OnAuthorization(filterContext As AuthorizationContext)
{
if (filterContext.HttpContext.Request.HttpMethod.ToUpper() == "POST")
{
AntiForgery.Validate();
}
}
}