Memfis
Memfis

Reputation: 93

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:

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:

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

Upvotes: 8

Views: 1823

Answers (2)

mode777
mode777

Reputation: 3187

In AspNetCore 1.1.0.0 (Maybe also in earlier versions) with a SPA scenario this is actually quite easy:

Make sure you deliver your index page from a .cshtml view and just add

@Html.AntiForgeryToken()

If you are using jquery you can then read this token and make sure it is sent with all future non-get requests inside a http-header

$(document).ajaxSend(function(e, xhr, options) {
    if (options.type.toUpperCase() != "GET") {
        xhr.setRequestHeader("RequestVerificationToken", $("input[name='__RequestVerificationToken']").val());
    }
});

Inside your controller method, just add

[HttpPost]
[ValidateAntiForgeryToken]
public string TestAntiForgery()
{
   return "success";
}

If you want/must use a differen header you can change it like this in configureServices:

services.Configure<AntiforgeryOptions>((options) =>
{
    // Configure a different header here
    options.HeaderName = "otherHeaderName";
});

Upvotes: 0

Maxime Rouiller
Maxime Rouiller

Reputation: 13699

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 then you could have a controller that depends on IHtmlGenerator and generate your token that way.

Upvotes: 1

Related Questions