Я хочу использовать AntiForgeryTokens
для каждого действия HttpPost, используя ActionFilter, который находится в контроллере с именем ControllerBase
, от которого наследуется каждый другой контроллер.
Я хочу сделать это, создав ActionFilter, наследуемый от ValidateAntiForgeryToken
, который принимает аргумент, указывающий, к каким HTTP-глаголам применять себя. Затем я хочу применить этот фильтр к ControllerBase
, чтобы убедиться, что AntiForgeryToken
проверяется для КАЖДОЙ операции POST на всем сайте.
Я изучал использование это решение, но
AuthorizationContext Constructor (ControllerContext)
— это устаревший конструктор, и я не уверен, как перестроить код, используя рекомендуемыйAuthorizationContext(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
.Похоже, что по умолчанию AntiForgeryToken не используется, поскольку я получаю следующую ошибку:A required anti-forgery token was not supplied or was invalid
после каждого действия с публикацией.
Как мне переписать мой ActionFilter, чтобы он соответствовал текущим неустаревшим стандартам и правильно использовал маркер защиты от подделки для каждого глагола [HttpPost]
?
Должен ли я сам включать токен защиты от подделки в каждую форму (думаю, да)? (в отличие от автоматического создания — не смейтесь, мне любопытно) Обновление: Как указано в комментариях; Да, это нужно делать с каждой формой.
Вот код из моей 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;
}
}
}
ControllerBase
для моей текущей архитектуры. - person Ecnalyr   schedule 02.08.2012public static MvcForm BeginSecureForm(this HtmlHelper htmlHelper, RouteValueDictionary routeValues) { var mvcForm = htmlHelper.BeginForm(routeValues); htmlHelper.ViewContext.Writer.Write(htmlHelper.AntiForgeryToken().ToHtmlString()); return mvcForm; }
- person felickz   schedule 07.11.2013