0

In an ASP.NET MVC application, we use @Html.AntiForgeryToken() in the user login form. Then in the controller, the [ValidateAntiForgeryToken] filter helps validate the token to prevent automated login attempt.

Now we are building angular apps and I wonder if we should add [ValidateAntiForgeryToken] to our ApiController, and how the Anti-forgery token will be generated in this situation. Any advice?

Blaise
  • 18,108
  • 20
  • 89
  • 154
  • Tokens are generated on the server, so it has nothing to do with angular. You can send the generated token from the server to the client and store it in a $window.sessionToken and send it back on subsequent requests to validate a user. – ribsies Feb 02 '15 at 19:59
  • As noted above, the token must be created on the server and not be predictable to the client. http://stackoverflow.com/questions/2906754/how-can-i-supply-an-antiforgerytoken-when-posting-json-data-using-ajax – New Dev Feb 02 '15 at 20:11

1 Answers1

2

We use this approach in our production systems.

  1. Create an HtmlExtensions method (let's call it AjaxAntiForgeryToken()) the token using System.Web.Helpers.AntiForgery.GetTokens(), and append the cookieToken and formToken into a String with a character delimiter that doesn't appear in the cookieToken or the formToken (e.g. ':'), as discussed in the link.

  2. Inject it into your angular application (we create an angular constant in the Razor template, and ensure that the constant is instantiated prior to initializing our application: e.g.

    angular.module('myapp.bootstrapper', []) .constant('AppSettings', { RequestToken: '@Html.AjaxAntiForgeryToken()' })

  3. We inject the AppSettings dependency in our app.js's .config function (or wherever the code for configuring and initializing your app may be), and then modify our $httpProvider to ensure that all calls from angular's $http service include the token from (1) in the header:

    `$httpProvider.defaults.headers.common['RequestVerificationToken'] = AppSettings.AuthToken || "no request verification token";` 
    
  4. Put the AjaxAntiForgeryTokenAttribute (as shown in the link) on the methods that you validated.

Brian Law
  • 166
  • 4
  • Brilliant! Since you are injecting `@Html.AjaxAntiForgeryToken()` into the angular app setter, I assume there is no separate `app.js` to define the angular app. The setter should be in a ` – Blaise Feb 02 '15 at 20:39
  • You're absolutely right, the setter is indeed in a ` – Brian Law Feb 02 '15 at 20:49