views:

913

answers:

4

I have to call some code in a SharePoint site that runs under the same service ID that the web application is running under. By default, SharePoint impersonates the user viewing the web page, and the users don't have the necessary permissions.

What is the best way to run some code using the web application's service ID, then revert back to using the default impersonation?

+4  A: 

SPSecurity.RunWithElevatedPrivileges

Nat
A: 

Under ASP I had a utility DLL that I could use to call Win32's RevertToSelf() function (found in the advapi32.dll) to get the ASP to run under the identity of the application pool.

Of course once there, there's no going back to the original identity the thread was using but that's not really a problem. Once the current request had ended, the next request would run again under the users identity (or the anonymous users).

You could probably do the same with PInvoke in ASP.NET but I wouldn't know what effect that might have on the framework. I'm certain it would last only for the current request. I don't think there is any standard .NET API to do this.

AnthonyWJones
Not appropriate for a SharePoint environment
Nat
A: 

easy! Wrap the calls you're making in a HostingEnvironment.Impersonate() block.

http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.impersonate.aspx

andrewbadera
+3  A: 

Nat is right. You should use SPSecurity.RunWithElevatedPrivileges. Under the covers it does a ReverToSelf that Anthony mentions, but it is much easier to use the helper method. You can use an inline delegate as in the following example.

The main thing to realize is that this delegate runs under a separate application domain which basically means that you want to use a SPSite or SPWeb you must re-instantiate them within the delegate as shown below.

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    // Your are now inside the delegate
    // Anything provided within this block is marshaled across the app domain
    using (SPSite site = new SPSite("http://myserver/sites/mysite"))
    {
        using (SPWeb web= site.OpenWeb())
        {
            // Do stuff here
        }
    }
});
Kirk Liemohn