簡體   English   中英

$ .post上沒有必填的防偽表單字段“ __RequestVerificationToken”

[英]The required anti-forgery form field “__RequestVerificationToken” is not present on $.post

目前,我的帖子中沒有顯示我的AntiForgeryToken的問題,但據我所知,它實際上在那里。

由於我不使用表單從HTML中獲取數據,而只是使用輸入字段,因此我使用以下命令在頁面底部制作了一個空表單:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = 
"__AjaxAntiForgeryForm" }))
{
    @Html.AntiForgeryToken()
}

這導致了我可以使用jQuery獲得的AntiForgeryToken。

所以在我的JavaScript中,我這樣做:

                        var LoginData = {
                            EmailAddress: currentMail,
                            Password: password
                        }
                        var form = $('#__AjaxAntiForgeryForm');
                        var token = $('input[name="__RequestVerificationToken"]', form).val();

                        data = {
                            __RequestVerificationToken: token,
                            LoginData: LoginData
                        }

                        $.post(window.location,
                            {
                                scController: '*Controller*',
                                scAction: 'ValidateLogin',
                                data: data
                            }).done(function (d, e) { 
                                console.log("done");
                                console.log(d);
                                console.log(e);
                            }).fail(function (d, e) {
                                console.log("error");
                                console.log(d);
                                console.log(e);
                            });

我創建的數據對象導致:

{LoginData: {EmailAddress: "********", Password: "*******"}, __RequestVerificationToken: "Imagine a token here"}

然后我的控制器動作:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ResultMessage ValidateLogin(LoginData login)
    {
        return _userRepository.Login(login);
    }

由於某些原因,當我嘗試執行此文章時,出現此錯誤:

“不存在必需的反偽造表單字段“ __RequestVerificationToken”。”

我究竟做錯了什么?

編輯1:我看到Cookie頭中的__RequestVerificationToken與我隨數據發送的__RequestVerificationToken不同。 怎么會這樣?

如此處所述https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks與ajax一起使用時,防偽必須在標頭中發送令牌,如下所示:

$.ajax("api/values", {
    type: "post",
    contentType: "application/json",
    data: {  }, // JSON data goes here
    dataType: "json",
    headers: {
        'RequestVerificationToken': <Token>
    }
});

這是我在此問題上的分步方法。 我正在使用angularJS,jquery,ASP.NET MVC 5 https://stackoverflow.com/a/57781976/2508781

使用MVC的AntiForgery.Validate()確實可以在這里驗證防偽令牌的值,並且到目前為止效果非常好。 希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM