CryptographicException:加密操作期间发生错误:如何自动修复它?

CryptographicException: Error occurred during a cryptographic operation : how can I automatically fix it?

这是我的Global.ascx.csFormsAuthentication

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

    protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
    {
        HttpCookie authCookie = Request.Cookies["CookieFA"];
        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

            CustomPrincipal principal = new CustomPrincipal(authTicket.Name);
            CustomPrincipalSerializeModel userSerializeModel = JsonConvert.DeserializeObject<CustomPrincipalSerializeModel>(authTicket.UserData);
            principal.UserID = userSerializeModel.ID;
            principal.FirstName = userSerializeModel.FirstName;
            principal.LastName = userSerializeModel.LastName;
            principal.Roles = userSerializeModel.RoleName.ToArray<string>();

            HttpContext.Current.User = principal;
        }
    }

    protected void Application_Error(object sender, EventArgs e)
    {
        Exception exception = Server.GetLastError();
        if (exception is CryptographicException)
        {
            FormsAuthentication.SignOut();

            Session.Abandon();

            // clear authentication cookie
            HttpCookie cookie1 = new HttpCookie("CookieFA", "");
            cookie1.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie1);

            // clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
            SessionStateSection sessionStateSection = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState");
            HttpCookie cookie2 = new HttpCookie(sessionStateSection.CookieName, "");
            cookie2.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie2);

            FormsAuthentication.RedirectToLoginPage();
        }
    }
}

但是(即使使用 Application_Error 方法),我仍然经常遇到此错误:

[CryptographicException: Error occurred during a cryptographic operation.]
   System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.HomogenizeErrors(Func`2 func, Byte[] input) +115
   System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.Unprotect(Byte[] protectedData) +70
   System.Web.Security.FormsAuthentication.Decrypt(String encryptedTicket) +9778338
   GPMS.MvcApplication.Application_PostAuthenticateRequest(Object sender, EventArgs e) in C:\repos\GPMS\GPMS\Global.asax.cs:32
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +141
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +71

已经尝试了 here 中的一些建议,但没有解决问题。

我不在 Azure 上。而且我不想使用解决方案"delete the cookies and al is ok":不能强制用户删除cookie。系统必须自动完成。

我在哪里可以修复它?也许我错过了全局错误处理程序的一些内容? 好像Application_Error不叫maybe?

像处理任何 cookie 一样处理无法解密的 cookie。

protected FormsAuthenticationTicket GetAuthTicket()
{
    HttpCookie authCookie = Request.Cookies["CookieFA"];
    if (authCookie == null) return null;
    try
    {
        return FormsAuthentication.Decrypt(authCookie.Value);
    }
    catch(System.CryptographicException exception)
    {
        _errorLog.Write("Can't decrypt cookie! {0}", exception.Message);
        return null;
    }
}

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
    var authTicket = GetAuthTicket();
    if (authTicket != null)
    {
        CustomPrincipal principal = new CustomPrincipal(authTicket.Name);
        CustomPrincipalSerializeModel userSerializeModel = JsonConvert.DeserializeObject<CustomPrincipalSerializeModel>(authTicket.UserData);
        principal.UserID = userSerializeModel.ID;
        principal.FirstName = userSerializeModel.FirstName;
        principal.LastName = userSerializeModel.LastName;
        principal.Roles = userSerializeModel.RoleName.ToArray<string>();

        HttpContext.Current.User = principal;
    }
}

不用说,您还应该调查为什么会发生这些异常,例如 if your machine key is changing 每个应用程序池回收。