【问题标题】:How to send AntiForgeryToken via AngularJs?如何通过 AngularJs 发送 AntiForgeryToken?
【发布时间】:2021-11-04 06:49:47
【问题描述】:

在我的 MVC 项目中,我通过 AngularJs 调用 method。我需要将AntiForgeryToken 发送到method

在视图中

@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
});

但是,它不起作用。

【问题讨论】:

    标签: angularjs asp.net-mvc


    【解决方案1】:

    试试这个

    this.data.__RequestVerificationToken = $('input[name="`__RequestVerificationToken`"]').val();
    .....
    
        data: this.data,
        dataType: 'JSON',
        contentType:'application/x-www-form-urlencoded; charset=utf-8',
    .....
    

    【讨论】:

    • @SYEDNAWAZPRINCE 对不起,diff net 版本,试试另一个
    【解决方案2】:

    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
        }
    

    【讨论】:

    • 代码放在哪里?在 mvc controller 或 AngularJs controller?
    • 将以上代码放入 Angular js 控制器中。
    • function 格式在js 文件中是不允许的
    • @SYEDNAWAZPRINCE 很抱歉回复晚了。那是我的错误,我没有解释清楚。我已经编辑了我的 cmets 以及所有必需的代码。我希望这对你有用。
    • @RajshKumarSwain,感谢您的回复。您使用了自定义过滤器MyValidateAntiForgeryTokenAttribute。但是,我想使用默认的ValidateAntiForgeryToken
    猜你喜欢
    • 2015-12-23
    • 2017-12-09
    • 2015-10-24
    • 2013-12-30
    • 1970-01-01
    • 2014-04-08
    • 2015-12-04
    • 2018-08-27
    • 1970-01-01
    相关资源
    最近更新 更多