Mark verb handlers with ValidateAntiForgeryToken
Mark verb handlers with ValidateAntiForgeryToken
Microsoft docsDescription
When designing an ASP.NET MVC controller, be mindful of cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET MVC controller. For more information, see XSRF/CSRF prevention in ASP.NET MVC and web pages.
This rule checks that ASP.NET MVC controller action methods either:
- Have the ValidateAntiforgeryTokenAttribute and specify allowed HTTP verbs, not including HTTP GET.
- Specify HTTP GET as an allowed verb.
Cause
An ASP.NET MVC controller action method isn't marked with ValidateAntiForgeryTokenAttribute), or an attribute specifying the HTTP verb, such as HttpGetAttribute) or AcceptVerbsAttribute.
How to fix violations
- For ASP.NET MVC controller actions that handle HTTP GET requests and don't have potentially harmful side effects, add an HttpGetAttribute to the method.
If you have an ASP.NET MVC controller action that handles HTTP GET requests and has potentially harmful side effects such as modifying sensitive data, then your application is vulnerable to cross-site request forgery attacks. You'll need to redesign your application so that only HTTP POST, PUT, or DELETE requests perform sensitive operations.
- For ASP.NET MVC controller actions that handle HTTP POST, PUT, or DELETE requests, add ValidateAntiForgeryTokenAttribute) and attributes specifying the allowed HTTP verbs (AcceptVerbsAttribute, HttpPostAttribute, HttpPutAttribute, or HttpDeleteAttribute). Additionally, you need to call the HtmlHelper.AntiForgeryToken() method from your MVC view or Razor web page. For an example, see Examining the edit methods and edit view.
Example
#pragma warning disable CA3147
// The code that's violating the rule is on this line.
#pragma warning restore CA3147When to suppress
It's safe to suppress a warning from this rule if:
- The ASP.NET MVC controller action has no harmful side effects.
- The application validates the antiforgery token in a different way.