Monday, January 25, 2010

Open SPSite under RunWithElevatedPrivileges in proper zone

Sometimes in Sharepoint development we need to run some code under SPSecurity.RunWithElevatedPrivileges() in order to execute it under System account. As you know if we use SPSecurity.RunWithElevatedPrivileges() we should reopen SPSite object in delegate passed to this method:

   1: SPSecurity.RunWithElevatedPrivileges(() =>
   2: {
   3:     using (var site = new SPSite(SPContext.Current.Site.ID))
   4:     {
   5:         ...
   6:     }
   7: });

This code works well if you have single zone configured for your web application (you can see zones for web applications in Central Administration -> Application Management -> Authentication Providers). But if you have several authentication zones for single web application it can lead to troubles: Sharepoint will always open SPSite in Default zone. I.e. even if code in example above is executed under Internet zone with FBA (e.g. under http://www.example.com) it will open SPSite object for Default zone which may use windows authentication (e.g. http://example). It in turn may lead to unclear bugs like Access denied, Operation is not valid due to the current state of object, etc.

In order to avoid this trouble use another constructor of SPSite class which receives additional parameter of type SPUrlZone:

   1: SPSecurity.RunWithElevatedPrivileges(() =>
   2: {
   3:     using (var site = new SPSite(SPContext.Current.Site.ID,
   4: SPContext.Current.Site.Zone))
   5:     {
   6:         ...
   7:     }
   8: });

With this code SPSite will be opened in proper zone.

No comments:

Post a Comment