Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the ValidateAntiForgeryToken globally

Security at first.

MVC best practices reccomend to add the [ValidateAntiForgeryToken] attribute to each [HttpPost] action.

How can I enforce this rule in one unique point of the application?

like image 618
Fabrizio Avatar asked Mar 06 '11 20:03

Fabrizio


People also ask

How does ValidateAntiForgeryToken work?

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.

What is ValidateAntiForgeryToken in asp net core?

June 09, 2020. AntiForgeryToken is a security token generated by the . Net Core web application, which is used to validate a post request to guard against Cross-Site Request.

How do I make an anti-forgery token?

AntiForgeryToken(String) To specify custom data to be embedded within the token, use the static AntiForgeryConfig. AdditionalDataProvider property. Generates a hidden form field (anti-forgery token) that is validated when the form is submitted. The field value is generated using the specified salt value.


1 Answers

The follwing class allow to do this with a FilterProvider

public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
{
    List<Filter> result = new List<Filter>();

    string incomingVerb = controllerContext.HttpContext.Request.HttpMethod;

    if (String.Equals(incomingVerb, "POST", StringComparison.OrdinalIgnoreCase))
    {
        result.Add(new Filter(new ValidateAntiForgeryTokenAttribute(), FilterScope.Global, null));
    }

    return result;
}

To use the above class add this to the RegisterGlobalFilters method in global.asx file:

...    
FilterProviders.Providers.Add(new AntiForgeryTokenFilterProvider ());
..

Doing this, each [HttpPost] will check if the Html.AntiForgeryToken() is in the view.

like image 89
Fabrizio Avatar answered Oct 05 '22 22:10

Fabrizio