Tuesday 20 September 2011

SPUserToken and the Impersonating process in Sharepoint 2010

Some times you will need to work with SPSecurity.RunWithElevatedPrieveleges but you will notice that if you follow that path you could end having a lot of trouble. So instead of going to the extreme with approach you can find a really nice class called SPUserToken class what is really easy to use.

What you, basically, it is tell to Sharepoint you are the system and you want to be able to perform some operations.

How? You just pass the parameter in the SPSite object when you open it:

SPUserToken _tUserToken= SPContext.Current.Site.SystemAccount.UserToken;
using(SPSite _sSite = new SPSite(SPContext.Current.Site.ID, _tUserToken= ))
{
     using (SPWeb _wWeb = _sSite.OpenWeb(SPContext.Current.Web.ID))
     {
       //## WRITE YOUR CODE HERE
     }
} 


You can always inherit the user token from a site:

SPSite _sSiteTemp = new SPSite(@"http://SHAREPOINTSITE");
SPUserToken _UserToken= _sSiteTemp.SystemAccount.UserToken;
using (SPSite _sSite= new SPSite(siteStr, systoken))
{
       using (SPWeb _wWeb= _sSite.OpenWeb())
       {
          //## WRITE YOUR CODE HERE
       }
}
   
if (_sSiteTemp!=null) _sSiteTemp.Dispose();


Conclusion: Remember, before using SPSecurity.RunWithElevatedPrieveleges think about this option.