Access denied with SPSecurity.RunWithElevated privileges


 

A fellow colleague was trying to do something in web part that required more privileges

So as all of us would do he wrapped the code round SPSecurity.RunWithElevatedPrivileges.

It is then he started receiving errors on access denied each time he tried to add the web part.

Below was his code

 

SPSecurity.RunWithElevatedPrivileges(delegate()

 

{

 

         SPSite site = SPContext.Current.Site;

 

         SPWeb web = SPContext.Current.Web;

 

         SPWebCollection webs = web.Webs;

...  

});//Close "SPSecurity.RunWithElevatedPrivileges" block

 

This code is not correct because of the lines below

SPSite site = SPContext.Current.Site;

SPWeb web = SPContext.Current.Web;

 

SPContext is something that exists and is not created from within RunWithElevatedPrivileges.  Hence only object created with ElevatedPriviliges give the user the elevated privileges.

Hence the below code should work fine.

 

SPSecurity.RunWithElevatedPrivileges(delegate()

{

         SPSite site = SPContext.Current.Site;

         SPWeb web = SPContext.Current.Web;

         string url = SPContext.Current.Web.Url;

         using (SPSite localSiteObj = newSPSite(url))

              {

            using (SPWeb localWebObj = localSiteObj.OpenWeb())

                   {       SPWebCollection webs = localWebObj.Webs;            }

              }

});//Close "SPSecurity.RunWithElevatedPrivileges" block

  

If you notice localSiteObj and localWebObj are created within elevatedPrivileges and hence would work fine.  You can use SPContext also within elevatedPrivileges but only to do stuff which does not need extra privileges.

Hope it clarifies

Comments (1)

  1. Anonymous says:

    Exactly what I was looking for.  Thanks helped a lot.

Skip to main content