AntiForgery Token implementation in WebAPI+Angular

2019-04-17 09:14发布

问题:

I have an HTMl app, which uses Web API and AngularJS. We are planing to implement AntiForgery token in the App. I have an Index.cshtml page in which I have added these code

@using System.Web.Helpers

@functions{
    public string GetAntiForgeryToken()
    {
        string cookieToken, formToken;
        AntiForgery.GetTokens(null, out cookieToken, out formToken);
        return cookieToken + ":" + formToken;                
    }
}

And added an input tag like this:

  <input id="antiForgeryToken" data-ng-model="antiForgeryToken" type="hidden" 
     data-ng-init="antiForgeryToken='@GetAntiForgeryToken()'" />

When I run the app, I am getting this error:

Error Message: CS0117: 'System.Web.Helpers.AntiForgery' does not contain a definition for 'GetTokens'

ref : Web API and ValidateAntiForgeryToken

Can anyone advice?

What am I missing? Or is there a better way to implement Antiforgery token validation?

回答1:

You're probably missing a reference but don't use hidden input. Add the AntiForgeryToken to the Header instead.

Client can simply request the token via a custom HtmlHelper and add it to the Request Header when the view is initialized:

@Html.RequestVerificationToken()

And the Action retrieves it and validates it.

The easiest way is to create an AntiForgeryValidate attribute to your Post Action that validates the token from the header request.

[AntiForgeryValidate]

Have a look at this:

http://blog.novanet.no/anti-forgery-tokens-using-mvc-web-api-and-angularjs/