Saturday, March 12, 2011

Restricted Elevation in SharePoint

There are times when we would need to perform certain operations that would require elevated privileges. If your IT team is not willing to allow you to provide the necessary actions on the system account or the application pool account with all the rights, but instead use appropriate service accounts shared by other application then you would do something like this.
SPUser userImpersonated = Web.Users[@"mydomain\impersonatedUser"];
SPSite site = new SPSite("http://mywebsite", userImpersonated.UserToken);
using (SPWeb web = site.OpenWeb())
{
 // This is the section where you will use the impersonated token to do the elevated job      
 lblMessage.Text = web.CurrentUser.LoginName;
}

instead of.

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(url))
    {
        using (SPWeb web = site.OpenWeb())
        {
     // This is the section where you will do the job that requires elevated permissions
 }
    }
});