我可以通过jQuery从结果登录页面中输入@ Html.AntiForgeryToken()键的形式更新新的结果吗?
如果是,这是推荐和安全吗?
我该怎么做?
编辑:
在布局我有不同的PartialViews:
部分登录:
<ul class="menudrt" id="headerLogin"> @{ Html.RenderAction(MVC.Account.LoginHeader()); } </ul>
而在另一部分,发送评论的可能性:
<div class="comentsform"> <!-- Comments form --> @{ Html.RenderAction(MVC.Comment.Create()); } </div>
要发送评论,用户必须登录,所以在登录后,注释表单需要更新AntiForgeryToken或我得到验证错误,因为现在不同的是,登录已经建立.
谢谢
解决方法
所以这里会发生什么:
>匿名用户导航到您的页面
>为注释表单生成一个防伪令牌,但该令牌包含一个空的用户名(因为在那一刻用户是匿名的)
>您正在使用AJAX电话登录
>用户将注释表单提交给服务器,并且令牌验证失败,因为初始令牌中包含的空用户名不同于当前验证的用户名.
所以你有几个选项来解决这个问题:
>在步骤3.不要使用AJAX调用.使用标准表单提交登录用户并将其重定向到最初请求的页面.评论表格当然会被重新加载,并为其生成正确的防伪令牌.
>登录后刷新防伪令牌
解决方案1的明显性并不能使其成为我的答案中的一个很好的候选人.让我们看看第二个解决方案如何实现.
但是首先让我们用一个例子来重现这个问题:
控制器:
public class HomeController : Controller { public ActionResult Index() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Login() { FormsAuthentication.SetAuthCookie("john",false); return Json(new { success = true }); } [HttpPost] [ValidateAntiForgeryToken()] public ActionResult Comment() { return Content("Thanks for commenting"); } }
〜/查看/主页/ Index.cshtml:
<div> @{ Html.RenderPartial("_Login"); } </div> <div id="comment"> @{ Html.RenderPartial("_Comment"); } </div> <script type="text/javascript"> $('#loginForm').submit(function () { $.ajax({ url: this.action,type: this.method,data: $(this).serialize(),success: function (result) { alert('You are Now successfully logged in'); } }); return false; }); </script>
〜/查看/主页/ _Login.cshtml:
@using (Html.BeginForm("Login",null,FormMethod.Post,new { id = "loginForm" })) { @Html.AntiForgeryToken() <button type="submit">Login</button> }
〜/查看/主页/ _Comment.cshtml:
@using (Html.BeginForm("Comment",FormMethod.Post)) { @Html.AntiForgeryToken() <button type="submit">Comment</button> }
现在,当您导航到主页/索引时,相应的视图将被渲染,如果您在没有登录的情况下按“注释”按钮,它将会工作.但是,如果您登录然后注释将失败.
所以我们可以添加另一个控制器操作,它将返回一个简单的Html.AntiForgeryToken调用部分视图,以生成一个新的令牌:
public ActionResult RefreshToken() { return PartialView("_AntiForgeryToken"); }
和相应的部分(〜/ Views / Home / _AntiForgeryToken.cshtml):
@Html.AntiForgeryToken()
最后一步是通过更新我们的AJAX调用刷新令牌:
<script type="text/javascript"> $('#loginForm').submit(function () { $.ajax({ url: this.action,success: function (result) { $.get('@Url.Action("RefreshToken")',function (html) { var tokenValue = $('<div />').html(html).find('input[type="hidden"]').val(); $('#comment input[type="hidden"]').val(tokenValue); alert('You are Now successfully logged in and can comment'); }); } }); return false; }); </script>