在的WebAPI + AngularJS应用防伪令牌实施 [英] AntiForgery Token implementation in WebAPI+AngularJS app

查看:221
本文介绍了在的WebAPI + AngularJS应用防伪令牌实施的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML应用程序,它使用Web API和AngularJS。我们刨去落实在App防伪标记。我有我已经添加了这些code的Index.cshtml页

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:

错误消息:CS0117:'System.Web.Helpers.AntiForgery'不包含一个定义为'GetTokens'

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

REF:的Web API和ValidateAntiForgeryToken

任何人都可以建议?

我在想什么?
或者是有实现防伪标记验证一个更好的办法?

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

推荐答案

你可能缺少一个参考,但不要使用隐藏输入。在AntiForgeryToken添加到页眉代替。

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

客户端可以简单地通过自定义的HtmlHelper请求令牌并将其添加到视图时初始化请求头:

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.

最简单的方法是创建一个AntiForgeryValidate属性来安置自己的行动验证从头部请求令牌。

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 。无/防伪令牌,使用-MVC的Web-API和angularjs /

这篇关于在的WebAPI + AngularJS应用防伪令牌实施的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆