1

This is my Global.ascx.cs, with FormsAuthentication:

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();
        }
    }
}

But still (even with that Application_Error method), I often got this 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

Already try some of the suggestions written here, but didn't fix the problem.

I'm not on Azure. And I don't want to use the solution "delete the cookies and al is ok": can't force users to delete cookie. The system must do it automatically.

Where can I fix it? Maybe I miss some on the Global error handler? It seems that Application_Error is not called maybe?

markzzz
  • 47,390
  • 120
  • 299
  • 507

1 Answers1

1

Handle an undecryptable cookie the same way you handle no cookie at all.

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;
    }
}

Needless to say, you should also investigate why these exceptions are happening, for example if your machine key is changing with each app pool recycle.

John Wu
  • 50,556
  • 8
  • 44
  • 80