在一个页面中以两种不同的forms使用多个@ Html.AntiForgeryToken()是否可能/正确?

我一直面临着@Html.AntiForgeryToken()严重问题。 我有一个注册控制器,它有一个创建视图来创建/注册新成员。 出于这个原因,我使用@Html.AntiForgeryToken()而不使用我的主提交表单中的任何SALT。 现在我想validation用户名是否已存在于我的用户名文本框的blur事件的数据库中。 为了validation,我编写了一个名为“Validation”的新控制器,并使用常量validationSALT编写了一个方法:

  [HttpPost] [ValidateAntiForgeryToken(Salt = @ApplicationEnvironment.SALT)] public ActionResult username(string log) { try { if (log == null || log.Length < 3) return Json(log, JsonRequestBehavior.AllowGet); var member = Membership.GetUser(log); if (member == null) { //string userPattern = @"^([a-zA-Z])[a-zA-Z_-]*[\w_-]*[\S]$|^([a-zA-Z])[0-9_-]*[\S]$|^[a-zA-Z]*[\S]$"; string userPattern = "[A-Za-z][A-Za-z0-9._]{3,80}"; if (Regex.IsMatch(log, userPattern)) return Json(log, JsonRequestBehavior.AllowGet); } } catch (Exception ex) { CustomErrorHandling.HandleErrorByEmail(ex, "Validate LogName()"); return Json(log, JsonRequestBehavior.AllowGet); } //found e false return Json(log, JsonRequestBehavior.AllowGet); } 

方法工作正常。 我已经使用HTTP Get annotation检查了没有[ValidateAntiForgeryToken]并且它给了我预期的结果。

我用谷歌搜索并检查了许多给定的解决方案,这些解决方案都不起作用。 对于我的validation控制器,我在同一页面中使用了另一个表单,并在Anti-forgery令牌中使用了SALT。

示例 :主提交表单的第一个防伪标记:

@using(Html.BeginForm(“Create”,“Register”)){@ Html.AntiForgeryToken()@ Html.ValidationSummary(true)…}

第二个防伪标记:

 
@Html.AntiForgeryToken(SALT)

在我使用的JavaScript中

  $(function () { AddAntiForgeryToken = function (data) { data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val(); return data; }; if ($("#LogName").length > 0) { $("#LogName").blur(function () { var user = $("#LogName").val(); var logValidate = "/Validation/username/"; //var URL = logValidate + user; //var token = $('#validation input[name=__RequestVerificationToken]').val(); data = AddAntiForgeryToken({ log: user }); $.ajax({ type: "POST", dataType: "JSON", url: logValidate, data: data, success: function (response) { alert(response); } }); }); } });  

在我的萤火虫中我得到了这个:

 log=admin&__RequestVerificationToken=NO8Kds6B2e8bexBjesKlwkSexamsruZc4HeTnFOlYL4Iu6ia%2FyH7qBJcgHusekA50D7TVvYj%2FqB4eZp4VDFlfA6GN5gRz7PB%2ByZ0AxtxW4nT0E%2FvmYwn7Fvo4GzS2ZAhsGLyQC098dfIJaWCSiPcc%2FfD00FqKxjvnqmxhXvnEx2Ye83LbfqA%2F4XTBX8getBeodwUQNkcNi6ZtAJQZ79ySg%3D%3D 

虽然已经过了但在cookie部分我得到了一个不同的cookie而不是传递一个:实际Cookie:

 ws5Dt2if6Hsah rW2nDly P3cW1smIdp1Vau 0TXOK1w0ctr0BCso/nbYu w9blq/QcrXxQLDLAlKBC3Tyhp5ECtK MxF4hhPpzoeByjROUG0NDJfCAlqVVwV5W6lw9ZFp/VBcQmwBCzBM/36UTBWmWn6pMM2bqnyoqXOK4aUZ4= 

我想这是因为我在一页中使用了2个防伪标记。 但在我看来,我应该使用2,因为第一个是生成提交发生,下一个需要validationvalidation。 然而,这是我的猜测,我认为我错了,因此我需要你们的帮助。

任何人都可以解释我应该使用两个防伪或一个的事实吗?

谢谢大家….

最后8个小时的挣扎给了我一个解决方案。

首先,是的,在页面中使用2个防伪标记是没有害处的。 第二,不需要将cookie与提供令牌相匹配。 提供令牌将始终不同,并将在服务器中进行validation。

如果我们使用[HttpGet]动作动词,则防伪令牌不起作用 。因为在防伪的validation过程中,通过从请求中检索Request.Form['__RequestVerificationToken']值来validation令牌。 参考: Steven Sanderson的博客:防止交叉……

方案

我修改了控制器:

 [HttpPost] [ValidateAntiForgeryToken(Salt = @ApplicationEnvironment.SALT)] //change the map route values to accept this parameters. public ActionResult username(string id, string __RequestVerificationToken) { string returnParam = __RequestVerificationToken; try { if (id == null || id.Length < 3) return Json(returnParam, JsonRequestBehavior.AllowGet); var member = Membership.GetUser(id); if (member == null) { //string userPattern = @"^([a-zA-Z])[a-zA-Z_-]*[\w_-]*[\S]$|^([a-zA-Z])[0-9_-]*[\S]$|^[a-zA-Z]*[\S]$"; string userPattern = "[A-Za-z][A-Za-z0-9._]{3,80}"; if (Regex.IsMatch(id, userPattern)) return Json(returnParam, JsonRequestBehavior.AllowGet); } } catch (Exception ex) { CustomErrorHandling.HandleErrorByEmail(ex, "Validate LogName()"); return Json(returnParam, JsonRequestBehavior.AllowGet); } //found e false return Json(returnParam, JsonRequestBehavior.AllowGet); } 

我在同一页面中的第一张表格:

 @using (Html.BeginForm("Create", "Register")) { @Html.AntiForgeryToken(ApplicationEnvironment.SALT) @Html.ValidationSummary(true) .... } 

我在同一页面中的第二张表格:

 **
@Html.AntiForgeryToken(ApplicationEnvironment.SALT)
**

我的jQuery解决了这个问题:

  $("#LogName").blur(function () { var user = $("#LogName").val(); var logValidate = "/Validation/username/"; $("#validation #id").val(user); **var form = $("#validation").serialize(); // a form is very important to verify anti-forgery token and data must be send in a form.** var token = $('input[name=__RequestVerificationToken]').val(); $.ajax({ **type: "POST", //method must be POST to validate anti-forgery token or else it won't work.** dataType: "JSON", url: logValidate, data: form, success: function (response) { alert(response); } }); });