Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct usage of AntiForgery token in ASP.NET 5 in SPA application?

In previous version of ASP.NET during SPA application the idea of AntiForgey token was following:

  • add @Html.AntiForgeryToken(); on the page
  • add __RequestVerificationToken to the request
  • ovverride AuthorizeAttribute as ValidateJsonAntiForgeryTokenAttribute.

I don't really understand the authorization requirements (is there some good information source?) in ASP.NET 5 but looks like new behavior should be like this:

  • add asp-anti-forgerytaghelper
  • add __RequestVerificationToken to the request
  • here should be the new requirement.

The question is: how to write this new authorization requirement and remove standard one? Could someone give some advice or point me on some example? Thanks

like image 776
Memfis Avatar asked Dec 16 '15 16:12

Memfis


Video Answer


1 Answers

With MVC6, if you use something like this:

<form asp-controller="Account" 
      asp-action="Login">
</form>

You will automatically get :

<form action="/Account/Login" method="post">
    <input name="__RequestVerificationToken" type="hidden" value="....">
</form>

asp-antiforgery would only be used if you want to deactivate that behavior.

As for the validation itself, it was added when you did app.AddMvc(...) in your ConfigureServices and Configure method.

In fact there's a bunch of stuff that is being added and if you are curious, you can check out the code!

If you really to generate this from an Action using ajax then you could have a controller that depends on IHtmlGenerator and generate your token that way.

like image 197
Maxime Rouiller Avatar answered Oct 04 '22 06:10

Maxime Rouiller