Home > front end >  ValidateAntiForgeryToken doesn't do the only thing it is suppose to do
ValidateAntiForgeryToken doesn't do the only thing it is suppose to do

Time:08-05

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:

  1. I tried both [ValidateAntiForgeryToken] and [ValidateAntiForgeryToken()], no difference!
  2. Someone said that the attribute only works in authorized controllers or actions. Tried this in my controller that has the [Authorize] tag.

PS: I have not added any code in my Startup.cs like services.AddMvc(...). Could it be something about that??

Please help.

CodePudding user response:

ValidateAntiForgeryToken is used to prevent cross-site request forgery attacks.

Antiforgery middleware has been added to the Dependency injection container when services.AddMvc() is called,and The FormTagHelper has injected antiforgery tokens into HTML form elements already.You don't need to call @Html.AntiForgeryToken()

For more details ,you could check this document.

CodePudding user response:

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.

  • Related