Running Code with Elevated Privileges

During custom development in Sharepoint, sometimes your code must call restricted methods within the Windows SharePoint Services object model even though the request is initiated by a non privileged user. In such cases you must be able to elevate the privilege of your code as it executes on web server.  Meaning, instead of your code running under the context of the current user, you’ll want to run it using an account with a higher level of access.

The RunWithElevatedPrivileges method is used to for this purpose.

VB.Net Example:

Sub GetSiteInfo()

Dim siteColl As SPSite = SPContext.Current.Site

Dim site As SPWeb = SPContext.Current.Web

Using ElevatedsiteColl As SPSite = New SPSite(siteColl.ID)

Using ElevatedSite As SPWeb = ElevatedsiteColl.OpenWeb(site.ID)

End Using

End Using

End Sub

After you write a method such as GetSiteInfo you can execute it with elevated privileges by invoking the RunWithElevatedPrivileges method and passing a delegate reference created with the Visual Basic AddressOf operator. (note the creation of new SPSite and SPWeb objects)

SPSecurity.RunWithElevatedPrivileges(AddressOf GetSiteInfo)

Note:

You cannot use the objects available through the Microsoft.SharePoint.SPContext.Current property, because those objects were created in the security context of the current user. You need to create an new instance of the SPSite class and the SPWeb class after you elevate the privileges of your code by calling RunWithElevatedPrivileges within the context of a Windows SharePoint Services request. 

You can find more details at:

http://msdn.microsoft.com/en-us/library/bb466220.aspx

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)