Access Denied error with RunWithElevatedPrivileges method

Sometime in SharePoint we need to run a piece of code under higher privileges in to achieve the target which is not possible with logged in user context. SharePoint provide us a method to achieve this which is under namespace Microsoft.SharePoint.

Method Name: SPSecurity.RunWithElevatedPrivileges

Example:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(web.Site.ID))
{
// implementation details omitted
}
});

In some situations we execute the code under above method but still got the access denied error. We wonder how this is possible as we are running code under user who has farm level full permissions.
Take a look at below code (looks neat right). We are trying to get the SPUser object of specific user which current user doesn’t have permissions. We should be aware when use the SPContext.Current.Web because it runs under current user context.
We must create a new SPWeb object under RunWithElevatedPrivileges method.

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(web.Site.ID))
{
// implementation details omitted
}
});

//Wrong code: Code will run under current user context
SPSecurity.RunWithElevatedPrivileges(delegate
{
SPUser user = SPContext.Current.Web.AllUsers[“UserName”];
});

//Correct Code: Code will run under system account context
SPSecurity.RunWithElevatedPrivileges(delegate
{
using(SPSite site = new SPSite(SPContext.Current.Site.ID))
{
using(SPWeb web = site.OpenWeb())
{
SPUser user = web.AllUsers[“UserName”];
}
}
});

Advertisements

About Rajan
I am Rajan Garg working as a Senior Software Engineer in a company. I am working on the Microsoft technologies.

One Response to Access Denied error with RunWithElevatedPrivileges method

  1. kiquenet says:

    Any final _solution_ with **full source code** sample application ? _IMHO, better samples for minimize learning curve are real

    applications with full source code and good patterns_

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: