Search code examples
c#performanceasp.net-mvc-3forms-authentication

What is the overhead on PostAuthenticateRequest?


I am implementing a custom ticket system using the Application_PostAuthenticateRequest method in my global.asax file (ASP.NET MVC). I'm wondering what the overhead for this kind of thing is - since it will deserialize some information on every request. It generates a cookie of around 1.8 kb, which is a ton - but is that a better alternative than frequent database trips?

Information being deserialized

  • User Id (int)
  • Roles (string[])
  • Email (string)
  • Associated Ids (int[]) // (hard to describe what these are, but each user will have around 3 of them)

It seemed smarter to implement a custom FormsAuthenticationTicket system than to continuously do round-trips to the database based on User.Identity.Name. But I'm just worried that this constant deserialization is very inhibitive. But it looks something like this...

    protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
    {
        HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

        if (authCookie != null)
        {
            string encTicket = authCookie.Value;

            if (!String.IsNullOrEmpty(encTicket))
            {
                // decrypt the ticket if possible.
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(encTicket);

                var userData = Deserializer.Deserialize(ticket);
                UserPrincipal principal = new UserPrincipal(userData);

                HttpContext.Current.User = principal;
            }
        }
    }

Here is the class being serialized as UserData in the FormsAuthenticationTicket.

[Serializable]
public class MembershipData
{
    public string Email
    {
        get;
        set;
    }

    public int Id
    {
        get;
        set;
    }

    public string[] Roles
    {
        get;
        set;
    }

    public int[] Ancillary
    {
        get;
        set;
    }
}

Solution

  • I would recommend you measuring the performance but I would expect that the cookie approach will be faster than doing roundtrips to the database. You could also simplify the serialization and make it as fast as possible by using a comma delimited or some special character delimited string. Here is how I would rank different operations in terms of performance:

    1. in-process communication
    2. inter-process communication
    3. inter-network communication