‘cacheRolesInCookie’ does not work with custom role providers

Earlier also I had heard and experienced that cacheRolesInCookie did not use to work with SharePoint 2007. When I was going through the fixes released in Service Pack 1 for SharePoint 2007, there was a mention of how it resolves the issue and actually cache the roles in a cookie and saves us a roundtrip to the data store.

But interestingly, when I created a custom provider and tried to reduce the DB calls, thought of using cacheRolesInCookie property, but sadly, it did not work as expected. Then that got me into a quest, why it is not working?

Digging down and checking around with my senior resources, came to know that it is very specifically going to work only with Microsoft.Office.Server.Security.LDAPRoleProvider. Then what should happen to my cute little custom provider?

A custom caching implementation !!!

But that was the only way found that could save me some DB trips at that time. So here goes the sample code that I used to do a custom caching for the roles.

    1: public override string[] GetRolesForUser(string username)
    2: {
    3:     string[] roleNames = null;
    4:     
    5:     // Get roles for user from HttpContext if it's already been loaded once this session
    6:     string cacheKey = _RolesCacheKey + this.Name + "_" + username;
    7:     HttpContext httpContext = HttpContext.Current;
    8:     if (httpContext != null)
    9:     {
   10:         MyRoleProviderCache roleNamesCache = 
   11:         (MyRoleProviderCache)httpContext.Cache.Get(cacheKey);
   12:         if (roleNamesCache != null)
   13:             return roleNamesCache.RoleNames;
   14:     }
   15:  
   16:     // Cache miss; load from MyStore and store into cache
   17:     roleNames = GetRolesForUser (username);
   18:     if (httpContext != null)
   19:     {
   20:         httpContext.Cache.Insert(cacheKey, new 
   21:         MyRoleProviderCache(roleNames), null, 
   22:         DateTime.Now.AddMinutes(_MyCacheDurationInMinutes), Cache.NoSlidingExpiration);
   23:     }
   24:  
   25:     return roleNames;
   26: }

 

As always, have fun and remember, these are just sample codes… feel free to implement them your own way image