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.
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.
Anti-forgery token validation is enabled by default in Razor Pages. You can disable validation either globally or on individual pages by using [IgnoreAntiforgeryToken] . You can prevent forms from creating anti-forgery tokens by using asp-antiforgery="false" in the form tag helper.
The basic purpose of ValidateAntiForgeryToken attribute is to prevent cross-site request forgery attacks. A cross-site request forgery is an attack in which a harmful script element, malicious command, or code is sent from the browser of a trusted user.
The IgnoreAntiforgeryToken filter is used to eliminate the need for an antiforgery token for a given action (or controller).
Anti-Forgery TokensThe server includes two tokens in the response. One token is sent as a cookie. The other is placed in a hidden form field. The tokens are generated randomly so that an adversary cannot guess the values.
You can disable the validation of anti-forgery tokens for an action by applying the [IgnoreAntiforgeryToken] attribute to a method.
[IgnoreAntiforgeryToken]
public IActionResult MyFunction()
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();
}
}
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.
Something along the lines of:
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)
{
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With