Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best option to custom Authentication using ASP .NET MVC (Cache, Cookie...)

I am a bit lost using Authentication with MVC...

I´m looking for the best option to use in a big E-Commerce site, where the performance is top priority...

The two options I´m looking until now are :

  • Create a FormsAuthenticationTicket and encrypt it into a cookie, like implemented here : Cookie implementation
  • Cache the Authentication data, like that :

    protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.User != null)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (HttpContext.Current.User.Identity is FormsIdentity)
                {
                    // Get Forms Identity From Current User
                    FormsIdentity id = FormsIdentity)HttpContext.Current.User.Identity;
                    // Create a custom Principal Instance and assign to Current User (with caching)
                    Customer principal = (Customer)HttpContext.Current.Cache.Get(id.Name);
                    if (principal == null)
                    {
                        // Create and populate your Principal object with the needed data and Roles.
                        principal = MyBusinessLayerSecurityClass.CreatePrincipal(id, id.Name);                            
                        HttpContext.Current.Cache.Add(
                        id.Name,
                        principal,
                        null,
                        System.Web.Caching.Cache.NoAbsoluteExpiration,
                        new TimeSpan(0, 30, 0),
                        System.Web.Caching.CacheItemPriority.Default,
                        null);
                    }
                    HttpContext.Current.User = principal;
                }
            }
        }
    }
    

Caching sample here

What you guys think?

Thanks

like image 922
Paul Avatar asked Nov 18 '10 11:11

Paul


1 Answers

A more MVCish way to achieve this is to write a custom AuthorizeAttribute and perform this in an overriden OnAuthorization method instead of using Application_AuthenticateRequest.

This being said I think that your implementation is quite good. As an alternative of storing the additional information into the cache you could store it in the userData part of the authentication ticket if this information is not very large of course. Both approaches are viable. If you decide to go with caching I would recommend you offloading it to dedicated cache servers instead of storing it in the memory of the web servers.

like image 124
Darin Dimitrov Avatar answered Oct 01 '22 20:10

Darin Dimitrov