我如何能在MVC 4使用AntiForgeryToken使用JSON职位(how can i use

2019-11-01 07:12发布

我有与JSON.stringify发布数据控制器类jQuery代码,但是当我用AntiForgeryToken,它不工作..是什么更好的办法,以确保JSON后或我错过了什么....

其次我需要附加到这个..即加密来保护JSON数据...

非常感谢先进的帮助...

<script type="text/javascript">

$(document).ready(function () {
    $('#id_login_submit').click(function () {

        var _authetication_Data = { _UserName: $('#u1').val(),  _Password: $('#p1').val() }

        $.ajax({
            type: "POST",
            url: "/Account/ProcessLoginRequest",
            data: JSON.stringify({ model: _authetication_Data }),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (response) {
                alert(response);
            }


        });

    });
});

 </script>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    @Html.LabelFor(m => m._UserName)
    @Html.TextBoxFor(m => m._UserName, new { id = "u1"})


    @Html.LabelFor(m => m._Password)
    @Html.PasswordFor(m => m._Password, new { id = "p1"})


    <input type="button" id="id_login_submit" value="Login" />
}

   [HttpPost]
    [ValidateAntiForgeryToken]
    public JsonResult ProcessLoginRequest(LoginModel model)
    {
        string returnString = null;

      if (ModelState.IsValid && WebSecurity.Login(model._UserName, model._Password, persistCookie: true))
        {
            returnString = "user is authenticated";
        }

        else
        { returnString = "Message from loginProcess"; }

        return Json(returnString, JsonRequestBehavior.AllowGet);
    }

Answer 1:

问题是,你不包括与您的要求VerificationToken:

var _authetication_Data = { _UserName: $('#u1').val(),  _Password: $('#p1').val(), __RequestVerificationToken: $('[name=__RequestVerificationToken]').val(); }


Answer 2:

这是我使用的代码

<script type="text/javascript">

$(document).ready(function (options) {
    $('#id_login_submit').click(function () {

        var token = $('input[name=__RequestVerificationToken]').val();

      //var token = $('input[name=__RequestVerificationToken]').val()+"999999";
     //   alert("token :: "+token);

        var _authetication_Data = { _UserName: $('#u1').val(), _Password: $('#p1').val(), "__RequestVerificationToken": token }


            $.ajax({
                type: "POST",
                url: "/Account/ProcessLoginRequest",
                data: JSON.stringify({ model: _authetication_Data }),
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                    alert(response);
                }
            });

    });
});



文章来源: how can i use AntiForgeryToken with JSON post in mvc 4