如何在 MVC 4 中使用 JSON 帖子测试反伪造令牌



我有 Json 发布到 MVC 4 Visual Studio 2012 控制器...我已经成功地将json数据与AntiForgeryToken一起传递给控制器,但我不知道如何准确测试它是否真的在"AntiForgeryToken的正确性"工作。此外,我尝试在客户端的__RequestVerificationToken代码中添加 9999,以查看它是否在服务器端进行验证并且确实如此!!.我的猜测是,如果我是对的,它不应该????这是我的代码

<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()+"99999";
//   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);
                }
            });
    });
});

@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: false))
        {
            returnString = "user is authenticated";     
        }
        else
        { returnString = "user not authenticated"; }
        return Json(returnString, JsonRequestBehavior.AllowGet);
    }

是的,你可以...但是您可以尝试使用serialize()方法。像这样:

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

当您使用serialize方法时,它会获取form标记中的所有元素并序列化为数据数组,类似于 { field: value, field2: value2, field3: value3 } ,并且 Token 将是隐藏的输入,因此,它将在序列化结果上。

有关更多信息,请查看文档:http://api.jquery.com/serialize/

它对我有用,实际上我没有使用表单,这是我的代码:

查看代码:

var token = $('input[name=__RequestVerificationToken]').val();        
        $.post(url, { Telefono: telefono, MensajeSMS: mensajeSMS, __RequestVerificationToken : token }, ...............

控制器方法,只需使用 apropiate 属性签名:

[验证防伪令牌] public JsonResult jsonEnviarSMS(string Telefono, string MensajeSMS)

最新更新