Thursday, November 20, 2008

Understanding RunWithElevatedPrivileges

What happens when you use RunWithElevatedPrivileges ?

Without RunWithElevatedPrivileges delegate the Sharepoint identity will be the same as of the current user identity and you are able to do whatever your own permissions allow you to do.

With RunWithElevatedPrivilages delegate the Sharepoint set the identity to Sharepoint\System. The Sharepoint\System identity doesn't have anything to do with a windows identity so you shouldn't be tempted to look for this windows account. The Sharepoint\Sytem is a built-in identity of Sharepoint and it has full permissions in Sharepoint. Also RunWithElevatedPrivilages elevates the windows privilages which means that if you are running the elevated code from a web application the applicaion is basically using the identity of the account running the webApp pool.

Incase of winforms/console application, code runs with your credentials (or if using 'runas', it would use whatever credentials you told it to use). There is no impersonation going on here like with the web application, so a call a to RunWithElevatedPrivileges will effectively do nothing because there is no impersonation to temporarily halt. You can see this is the case if you were to execute this code snippet in a console application:

using (SPSite site = new SPSite(siteUrl))
using (SPWeb web = site.OpenWeb(webUrl))

Note here that web.CurrentUser.LoginName is coming from the WSS identity. If you 'runas' the web application's app pool identity, it would get correlated to SharePoint\System and thats what you would see on the first line of output.