首页 > 解决方案 > 如何通过 AngularJs 发送 AntiForgeryToken?

问题描述

在我的 MVC 项目中,我method由 AngularJs 调用。我需要发送AntiForgeryTokenmethod.

在视图中

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    ...
}

在 MVC 中controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Model model)
{
  ...
}

在 AngularJs 中controller

this.data.Name= $('#txtNm').val();
this.data.Id = $('#Id').val();
var token = angular.element("input[name='__RequestVerificationToken']").val();

$http({
method: "POST",
url: "/Students/Create",
dataType: 'json',
data: this.data,
headers: {
  '__RequestVerificationToken': token
 }
}).then(function (response) {
                //success
}, function (response) {
                //error
});

但是,它不起作用。

标签: angularjsasp.net-mvc

解决方案


1-CSHTML

令牌是通过调用 AntiForgery.GetTokens 方法在服务器上生成的。

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


            }
    </script>

 @Html.AntiForgeryToken()
 <input name="RequestVerificationToken" data-ng-model="RequestVerificationToken" type="hidden" data-ng-init="RequestVerificationToken='@GetAntiForgeryToken()'" />

2-MVC 控制器

处理请求时,从请求标头中提取令牌。然后调用 AntiForgery.Validate 方法来验证令牌。如果令牌无效,Validate 方法将引发异常。

对于验证 AntiForgeryToken,我使用了 MyValidateAntiForgeryTokenAttribute()。

[HttpPost]
        [MyValidateAntiForgeryTokenAttribute()]
        public ActionResult Create()
        {
            // Your students create logic will be here
        }

         [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
        public class MyValidateAntiForgeryTokenAttribute : FilterAttribute
        {
            private void ValidateRequestHeader(HttpRequestBase request)
            {
                string cookieToken = String.Empty;
                string formToken = String.Empty;
                string tokenValue = request.Headers["__RequestVerificationToken"];
                if (!String.IsNullOrEmpty(tokenValue))
                {
                    string[] tokens = tokenValue.Split(':');
                    if (tokens.Length == 2)
                    {
                        cookieToken = tokens[0].Trim();
                        formToken = tokens[1].Trim();
                    }
                }
                AntiForgery.Validate(cookieToken, formToken);
            }

3-Angular JS 控制器

在 http 调用中分配标头 $scope.RequestVerificationToken

        '__RequestVerificationToken': $scope.RequestVerificationToken
    }

推荐阅读