Pages

Wednesday, August 7, 2013

Checking the FormsAuthentication cookie size is within 4096 bytes

I recently encountered an issue with the FormsAuthentication cookie not being set for certain users.

It turns out the cause was the total cookie size exceeding 4096 bytes and the browser not accepting it.

Aside from fixing the root cause and as a preventative measure for the future, I've added something like the following to detect the excessive cookie size. Note that this is a bit approximate as it doesn't take into account the cookie name, expiry date, etc...

    FormsAuthenticationTicket ticket = // Separate code to setup the authentication, including the UserData

    string hash = FormsAuthentication.Encrypt(ticket);
    int maxByteSize = 4000; // Max Cookie Size is 4096 including Cookie Name, Expiry, etc...
    if (System.Text.ASCIIEncoding.ASCII.GetByteCount(hash) > maxByteSize) 
    {
        // Raise the alarm that the cookie is going to get rejected by the browser
    }
    
    // Continue with standard cookie setup...
    HttpCookie formsAuthCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);

No comments:

Post a Comment