【问题标题】:anti-forgery token issue on browser back and resubmit浏览器上的防伪令牌问题返回并重新提交
【发布时间】:2015-12-25 07:13:45
【问题描述】:

在我的 MVC5 应用程序中,实现了防伪令牌。当用户启动并登录时,它可以工作。如果用户在登录后单击浏览器并使用不同的凭据重新提交,则会显示

The provided anti-forgery token was meant for user "xxxx", but the current user is "yyyy"

在登录控制器中,我尝试过类似

public ActionResult Index()
{
    if (User != null && (User.Identity.IsAuthenticated || User.Identity.Name != ""))
    {
        FormsAuthentication.SignOut();
        Session.Abandon();
        return RedirectToAction("Index");
    }
    return View();
}

但在这种情况下,系统不会触发该操作。

【问题讨论】:

  • 您能解释一下“启动和登录”是什么意思吗?
  • 启动应用程序并登录系统

标签: c# login asp.net-mvc-5 form-submit antiforgerytoken


【解决方案1】:

当我们有防伪令牌时,这很常见。

发生这种情况是因为防伪令牌将用户的用户名作为加密令牌的一部分嵌入,以便更好地进行验证。什么时候 您首先调用@Html.AntiForgeryToken() 用户未登录 所以令牌将有一个空字符串作为用户名,在 用户登录,如果您不更换防伪令牌,则不会 通过验证,因为初始令牌用于匿名用户并且 现在我们有了一个具有已知用户名的认证用户。

你有几个选项来解决这个问题:

1- 就在这一次让你的应用程序做一个完整的 POST 并且当 页面重新加载它将具有一个带有更新的防伪令牌 用户名嵌入。

2- 仅使用 @Html.AntiForgeryToken() 和正确的部分视图 登录后,执行另一个 AJAX 请求并替换您现有的 带有请求响应的防伪令牌。

3- 只需禁用身份检查和防伪验证 施行。将以下内容添加到您的 Application_Start 方法中: AntiForgeryConfig.SuppressIdentityHeuristicChecks = true。

针对 AntiForgeryToken 运行的验证代码还会检查您的登录用户凭据是否未更改——这些凭据也在 cookie 中进行了加密。这意味着,如果您在弹出窗口或其他浏览器选项卡中登录或退出,您的表单提交将失败并出现以下异常:

System.Web.Mvc.HttpAntiForgeryException (0x80004005):
The provided anti-forgery token was meant for user "xxxx", but the current user is "yyyy".

您可以通过设置 AntiForgeryConfig.SuppressIdentityHeuristicChecks = true; 来关闭它。在 Global.asax 文件中的 Application_Start 方法中。

当 AntiForgeryToken 未验证您的网站时,将抛出 System.Web.Mvc.HttpAntiForgeryException 类型的异常。您可以通过捕获 HttpAntiForgeryException 至少为用户提供针对这些异常的更多信息页面,从而使这更容易一些。

private void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();

    if (ex is HttpAntiForgeryException)
    {
        Response.Clear();
        Server.ClearError(); //make sure you log the exception first
        Response.Redirect("/error/antiforgery", true);
    }
}

Here 是类似问题的 SO 线程。

additional 参考。

【讨论】:

  • AntiForgeryConfig.SuppressIdentityHeuristicChecks = true 对我不起作用 :( 使用 Asp.NET MVC 5...我一直在寻找 MVC 5 解决方案,但仍然没有找到。
【解决方案2】:

装饰您的登录 GET 方法
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult Login(...)

防止页面被缓存。这将强制在没有先前登录的用户用户名的情况下创建新令牌。

【讨论】:

    猜你喜欢
    • 2013-11-27
    • 1970-01-01
    • 2011-03-09
    • 2011-11-07
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    相关资源
    最近更新 更多