44

我在使用 ASP.Net MVC 中的 AntiForgeryToken 时遇到问题。如果我在我的网络服务器上执行 iisreset 并且用户继续他们的会话,他们会被退回到登录页面。不可怕,但是 AntiForgery 令牌爆炸了,唯一的办法就是把浏览器上的 cookie 炸掉。

使用版本 1 的 beta 版本时,它在为我读回 cookie 时经常出错,所以我过去常常在请求验证令牌之前对其进行清理,但在它发布时已修复。

现在我想我会回滚到修复测试版问题的代码,但我不禁认为我错过了一些东西。有没有更简单的解决方案,我应该放弃他们的助手并从头开始创建一个新的吗?我觉得很多问题在于它与旧的 ASP.Net 管道如此紧密地联系在一起,并试图将其混入做一些它并不是真正设计要做的事情。

我查看了 ASP.Net MVC 2 RC 的源代码,看起来代码没有太大变化,所以虽然我没有尝试过,但我认为那里没有任何答案。

这是异常堆栈跟踪的相关部分。

编辑:我刚刚意识到我没有提到这只是试图在 GET 请求中插入令牌。这不是在您启动 POST 时发生的验证。

System.Web.Mvc.HttpAntiForgeryException: A required anti-forgery token was not
supplied or was invalid.
---> System.Web.HttpException: Validation of viewstate MAC failed. If this 
application is hosted by a Web Farm or cluster, ensure that <machineKey> 
configuration specifies the same validationKey and validation algorithm. 
AutoGenerate cannot be used in a cluster.
---> System.Web.UI.ViewStateException: Invalid viewstate. 
  Client IP: 127.0.0.1
  Port: 4991
  User-Agent: scrubbed
  ViewState: scrubbed
  Referer: blah
  Path: /oursite/Account/Login
---> System.Security.Cryptography.CryptographicException: Padding is invalid and
cannot be removed.
at System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast)
at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
at System.Security.Cryptography.CryptoStream.FlushFinalBlock()
at System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, IVType ivType, Boolean useValidationSymAlgo)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
--- End of inner exception stack trace ---
--- End of inner exception stack trace ---
at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError)
at System.Web.UI.ViewStateException.ThrowMacValidationError(Exception inner, String persistedState)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState)
at System.Web.Mvc.AntiForgeryDataSerializer.Deserialize(String serializedToken)
--- End of inner exception stack trace ---
at System.Web.Mvc.AntiForgeryDataSerializer.Deserialize(String serializedToken)
at System.Web.Mvc.HtmlHelper.GetAntiForgeryTokenAndSetCookie(String salt, String domain, String path)
at System.Web.Mvc.HtmlHelper.AntiForgeryToken(String salt, String domain, String path)
4

6 回答 6

44

If your MachineKey is set to AutoGenerate, then your verification tokens, etc won't survive an application restart - ASP.NET will generate a new key when it starts up, and then won't be able to decrypt the tokens correctly.

If you are seeing this a lot, I'd suggest:

  1. Configuring a static MachineKey (you should be able to do this at the application level), see "How to: Configure a MachineKey" for more information
  2. Try not to perform IIS Resets when the site is being used1

1 The best way to do this is by having a loadbalanced application, which will require you to set a static MachineKey. Another option is to take the site down by placing a file named app_offline.htm in the root of the site, which will take the site offline and display your message - at least the users will expect things to go wrong.

于 2010-02-05T13:39:57.003 回答
15

现在我已经使用了一个解决方案,如果抛出异常,它会清除 cookie。如果再次抛出异常,我将让它原样发生。

我暂时不会将此标记为“答案”,希望有人有更好的答案。

public static class MyAntiForgeryExtensions
{
    // Methods
    public static string MyAntiForgeryToken(this HtmlHelper helper)
    {
        return MyAntiForgeryToken(helper, null);
    }

    public static string MyAntiForgeryToken(this HtmlHelper helper, string salt)
    {
        string fragment;
        string path = helper.ViewContext.HttpContext.Request.ApplicationPath;
        try
        {
            fragment = helper.AntiForgeryToken(salt, null, path);
        }
        catch (HttpAntiForgeryException)
        {
            // okay, scrub the cookie and have another go.
            string cookieName = GetAntiForgeryTokenName(path);
            helper.ViewContext.HttpContext.Request.Cookies.Remove(cookieName);
            fragment = helper.AntiForgeryToken(salt, null, path);
        }
        return fragment;
    }

    #region AntiForgeryData code that shouldn't be sealed
    // Copied from AntiForgeryData since they aren't accessible.
    internal static string GetAntiForgeryTokenName(string appPath) {
        if (String.IsNullOrEmpty(appPath)) {
            return "__RequestVerificationToken";
        }
        else {
            return "__RequestVerificationToken_" + Base64EncodeForCookieName(appPath);
        }
    }
    private static string Base64EncodeForCookieName(string s) {
        byte[] rawBytes = Encoding.UTF8.GetBytes(s);
        string base64String = Convert.ToBase64String(rawBytes);

        // replace base64-specific characters with characters that are safe for a cookie name
        return base64String.Replace('+', '.').Replace('/', '-').Replace('=', '_');
    }
    #endregion
}
于 2010-02-05T11:27:59.697 回答
11

我遇到了这个问题,要解决您需要做的就是在您的网络配置中添加一个显式机器密钥...

<machineKey validationKey="D82960E6B6E9B9029D4CAB2F597B5B4AF631E3C182670855D25FBDE1BFAFE19EFDE92ABBD1020FC1B2AE455D5B5F8D094325597CE1A7F8B15173407199C85A16" decryptionKey="577404C3A13F154908D7A5649EEC8D7C8A92C35A25A3EC078B426BB09D426A71" validation="SHA1" decryption="AES" /> 

确保将其放置在 web.config 内...

<system.web>
于 2013-06-21T09:59:46.580 回答
7

您可以添加AntiForgeryConfig.SuppressIdentityHeuristicChecks = true;global.asax

protected void Application_Start() {
    AntiForgeryConfig.SuppressIdentityHeuristicChecks = true;
}
于 2013-12-06T10:29:35.937 回答
4

实际上,我发现这在我的登录操作中起作用:

    public ActionResult LogOn()
    {
        formsAuthentication.SignOut();

        Response.Cookies.Clear();

        Session[SessionKeys.USER_SESSION_KEY] = null;
        Session.Clear();
        Session.Abandon();


        return View();
    }

重要的部分是:Response.Cookies.Clear();

于 2010-03-27T18:26:20.223 回答
4

如果我在我的网络服务器上执行 iisreset 并且用户继续他们的会话,他们会被退回到登录页面。

没有理由iisreset将用户带到登录页面。如果您使用 cookie 跟踪身份验证信息并拥有无状态应用程序,则即使在服务器重新启动后用户也应该保持身份验证(当然,如果在重置期间发出请求,它将失败)。

于 2010-02-05T10:50:26.383 回答