Understand SPSecurity.RunWithElevatedPrivileges

Here is a Nice and simply explained article I’ve found while I was digging the blogs and posts for finding a solution to remove a ListItem from a List using another one’s credentials.

http://blogs.msdn.com/b/sowmyancs/archive/2008/08/14/spsecurity-runwithelevatedprivileges-an-important-point-while-using-it-in-web-context.aspx

My Scenario

What i was faced was, i wanted to remove a row from the SPList using SPSecurity.RunWithElevatedPrivileges . My WebApplication was Claims Based, and i was able to perfectly remove an item from the list when i perform it using my own credentials. The problem occurred when another person tried to do the same operation using his credentials.

Here the problem was, whenever we take the SPWeb instance using  

SPWeb oWeb = SPContext.Current.Web;, then SPWeb instance still running under anonymous account only , because we are taking it through the current web context in which the current user is running under anonymous account (IUSR_MachineName). That was the reason that we got that “Access Denied” exception. We need to remember this point all time whenever we use RunWithElevatedPrivileges under the web context.

So what we need to that, we have to take the current context outside the SPSecurity.RunWithElevatedPrivileges block and then create a new instance of SPSite and SPWeb inside the that block which will run under application pool identity.

Solution Code:

 SPWeb oWeb1 = SPContext.Current.Web; // taking the current SPWeb context running under the anonymous account
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite oSite = new SPSite(oWeb1.Site.Url))
                {
                    // creating a new SPSite running under Application pool idenity
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                      // Code Lines you need 
                    }
                }
            });

Good luck..!!
Advertisements

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