asp.net-mvc – 在一个页面中以两种不同的形式使用多个@ Html.AntiForgeryToken()是否可能/正确?

我一直面临严重的问题@ Html.AntiForgeryToken().我有一个注册控制器,创建/注册新成员.因此,我使用@ Html.AntiForgeryToken(),而不在我的主提交表单中使用任何SALT.现在我想验证用户名,如果它已经存在于我的用户名文本框的blur事件的数据库上.对于这个验证,我写了一个名为“验证”的新控制器,并写了一个常量验证SALT的方法
[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);

    }

方法工作正常我没有[ValidateAntiForgeryToken]检查HTTP Get注释,并给我预期的结果.

我已经google了,并且检查了许多给定的解决方案,没有一个这样的工作.对于我的验证控制器,我在同一个页面中使用了另一个表单,并在防伪令牌中使用了一个SALT.

例:
主要提交表单的防伪令牌:

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

第二个防伪令牌:

<form id="__AjaxAntiForgeryForm" action="#" method="post">
    @Html.AntiForgeryToken(SALT)
</form>

在javascript中我使用了这个

<script type="text/javascript" defer="defer">
    $(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);
                    }
                });

            });

        }
    });
</script>

在我的火焰中,我得到了:

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,因为第一个生成提交发生,下一个需要验证验证.然而,这是我的猜测,我认为我错了,因此我需要你们的帮助.

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

先谢谢大家….

解决方法

最后8个小时的奋斗给了我一个解决方案.

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

如果我们使用[HttpGet]动作动词,反伪造币不起作用.因为在反伪造的验证过程中,令牌通过从请求中检索Request.Form [‘__ RequestVerificationToken’]值来验证.参考:Steven Sanderson’s blog: prevent cross…

解决方案:

修改控制器:

[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,"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)
    ....
}

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

**<form id="validation">
    <!-- there is harm in using 2 anti-forgery tokens in one page-->
    @Html.AntiForgeryToken(ApplicationEnvironment.SALT)
    <input type="hidden" name="id" id="id" value="" />
</form>**

我的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",data: form,success: function (response) {
                    alert(response);
                }
            });
        });

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“WPF...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这...
Some samples are below for ASP.Net web form controls:(from http://www.visualize.uk.com/resources/asp
问题描述: 对于未定义为 System.String 的列,唯一有效的值是(引发异常)。 For columns not defined as System.String, the only vali
最近用到了CalendarExtender,结果不知道为什么发生了错位,如图在Google和百度上找了很久,中文的文章里面似乎只提到了如何本地化(就是显示中文的月份)以及怎么解决被下拉框挡住的问题,谈
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence changed a lot since 1.1. Here is the order: App
静态声明: &#39; Style=&quot;position: relative&quot; AppendDataBoundItems=&quot;True&quot;&gt; (无 或 空 或
以下内容是从网络上搜集资料,然后整理而来的。不当之处,请不吝指教。(The following were from network, and edited by myself. Thanks in a
Imports System Imports System.Reflection Namespace DotNetNuke &#39;*********************************
Ok so you have all seen them: “8 million tools for web development”, “5 gagillion tools that if you
以下内容来源于: http://blog.csdn.net/cuike519/archive/2005/09/27/490316.aspx 问:为什么Session在有些机器上偶尔会丢失? 答:可能和
以下文章提到可以用“http://localhost/MyWebApp/WebAdmin.axd”管理站点: ---------------------------------------------
Visual Studio 2005 IDE相关的11个提高开发效率的技巧 英文原创来源于: http://www.chinhdo.com/chinh/blog/20070920/top-11-vis
C#日期格式化 from: http://51xingfu.blog.51cto.com/219185/46222 日期转化一 为了达到不同的显示效果有时,我们需要对时间进行转化,默认格式为:2007
from: http://www.nikhilk.net/UpdateControls.aspx Two controls that go along with the UpdatePanel and
Open the report in the Designer. In the ToolBox, select/expand the &quot;Report Items&quot; section.
from: http://drupal.org/node/75844 Do this: find which TinyMCE theme you are using. For the sake of
asp.net中给用户控件添加自定义事件 用户控件中定义好代理和事件: public delegate void ItemSavedDelegate(object sender, EventArgs
在Windows版本的Safari中浏览以下的页面。 http://www.asp.net/AJAX/Control-Toolkit/Live/Calendar/Calendar.aspx Calen
http://aspnet.4guysfromrolla.com/articles/021506-1.aspx By Scott Mitchell Introduction When creating