0

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?

Community
  • 1
  • 1
Vipin Menon T P
  • 83
  • 1
  • 3
  • 14

1 Answers1

2

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/

Dynamic
  • 1,553
  • 2
  • 19
  • 25
  • I have gone through the link. Issue I find is, where to add the MVC HTML Helper Extension? My client is a pure html+AngulaJS project. – Vipin Menon T P Aug 25 '14 at 09:27
  • @Html refers to HtmlHelper class which is a C# class so if you don't have access to C# and ASP.NET MVC, you can't take this approach. It should be extended on the server side. – Dynamic Aug 26 '14 at 13:25
  • I created a wrapper class. I added a cs file to the app, where I wrote the GetToken() method and then I called it from my cshtml. Through that, I was able to overcome the dll issue. For everything I did what the blog said and it works fine :) – Vipin Menon T P Aug 29 '14 at 13:16
  • Hi Vipin, Can you please provide more details on how the issue is resolved without @Html.RequestVerificationToken() line? I am looking for a way to achieve this but since its just pure HTML I am unable to figure out how to achieve this. – G_S Mar 18 '16 at 17:43