AntiForgery Token implementation in WebAPI+AngularJS app

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-22 01:18:29

问题


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/



来源:https://stackoverflow.com/questions/25448204/antiforgery-token-implementation-in-webapiangularjs-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!