Run With Elevated Privilges

SharePoint Short #20

Instead of explicitly wrapping code in a RunWithElevatedPrivileges block, it’s better to first check if the user has sufficient privileges and only elevate when they don’t.

Instead of:

SPSecurity.RunWithElevatedPrivileges(() =>
    {
        // elevated code...
    });

Do this:

public void RunWithElevatedPrivileges(SPWeb web, SPSecurity.CodeToRunElevated elevatedCode)
{
    if (web.CurrentUser.IsSiteAdmin)
    {
        elevatedCode();
        return;
    }
    SPSecurity.RunWithElevatedPrivileges(elevatedCode);
}
 
public void TestMethod()
{
    RunWithElevatedPrivileges(SPContext.Current.Web, ()=>
        {
            // elevated code...
        });
}

This way the code will only be encapsulated in the elevated block when the user does not have adequate permissions and you’ll help to increase the performance of your code by avoiding executing unnecessary code.

You could further extend this by only opening the SPSite\SPWeb object when elevating the code.

This entry was posted in SharePoint, SharePoint Shorts and tagged . Bookmark the permalink.
0 0 votes
Article Rating
Subscribe
Notify of
guest

Solve the maths problem shown below before posting: *

0 Comments
Inline Feedbacks
View all comments