Friday, April 30, 2010

Impersonation technique using the SPUserToken in share point

Recently I had a requirement where I have share point list say with 10 items and item level permissions is set for each of the item.Assume that a user user1 has permission only for first 4 items,user2 only for next 3 items and user3 only for last 3 items.

Then I need to query this share point list with CAML query to fetch the items based on some criteria based on logged-in user. However as each user have only read permission and that too on few items the query using object module was giving access denied error.

So I had no other option other than to run the code with elevated privileges. I used impersonation technique using SPUserToken and SPSite class.
To impersonate the system I used the SystemAccount.UserToken property of the current SPSite context like
SPSite sharepointSite = new SPSite(SPContext.Current.Site.ID,SPContext.Current.Site.SystemAccount.UserToken);
then SPWeb object as

SPWeb sharepointWeb = sharepointSite.OpenWeb();
finally my sharepoint list as
SPList sharepointList = sharepointWeb.Lists["My List Name"];
and everything worked.