I am implementing AntiForgeryToken feature to my asp.net core mvc project. As usual, I have included @Html.AntiForgeryToken()
inside the form tags so it looks like this:
<form method="post" action="mycontroller/myaction">
@Html.AntiForgeryToken()
<input type="text" name="myInput"/>
<button type="submit">Submit</button>
</form>
and as you can imagine, here is the myaction action in my mycontroller controller:
[HttpPost]
[Route("somepath")]
[ValidateAntiForgeryToken]
public IActionResult myaction()
{
//some code here
}
Now the problem is, I NEVER GET ANY ERROR!!
I removed the @Html.AntiForgeryToken
from the view and the [ValidateAntiForgeryToken]
doesn't do a thing! the post action works just fine.
Here are two things I have tried that might give you a clue:
[ValidateAntiForgeryToken]
and [ValidateAntiForgeryToken()]
, no difference![Authorize]
tag.PS: I have not added any code in my Startup.cs
like services.AddMvc(...)
. Could it be something about that??
Please help.
In and MVC app (which you have there), request verification using an anti forgery token is opt in. You opt in by decorating the controller action with the [ValidateAntiForgeryToken]
attribute. If you omit the attribute, the request is not subject to verification. In each of the scenarios you described, there is no reason for an error. The only time you are likely to see an error (in the shape of a 400 HTTP status code) in an MVC app is if you decorate the action with the [ValidateAntiForgeryToken]
attribute but the cookie or token are not included as part of the request payload.
In Razor Pages, all POST requests are verified by default. You can opt out of request verification, in which case you can opt in on a page by page basis by adding the attribute to the PageModel class (not the handler method) The anti-forgery token is generated by the form tag helper when the method is set to POST in both Razor Pages and MVC views.
Sometimes, you might want to post without a form (using AJAX most commonly) in which case you need to generate the anti-forgery token in the view so that you can include it within the post request payload. The Html.AntiforgeryToken
helper (which is a legacy from older versions of MVC) provides a convenient way to do that.
I've written in detail about this process here: https://www.learnrazorpages.com/security/request-verification