Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I have a custom webservice hosted in SharePoint. Within this service, I need to at times look up sites by id. Despite running code in an SPSecurity.RunWithElevatedPriviledges block, I still get Access exceptions for non-admin users when trying to look up a site by id.

From what I've read, I may be able to get around this problem by opening the site collection using a User token for an admin account. My problem is, how do I get a user token for an admin account?

Any help is greatly appreciated.

Example:

//Putting this inside RunWithElevatedPrivileges causes it to fail
var siteCollection = new SPSite(SITE_COLLECTION_URL);

SPSecurity.RunWithElevatedPrivileges(() =>
{
    //This throws for non-admins, regardless of being in a RunWithElevatedPriviledges block
    var web = siteCollection.AllWebs[webId]); 
}
share|improve this question
    
RunWithElevatedPriviledges can be quirky. Can you please post the full block of code, including where the reference to the SPSite object is? –  Dave Wise Jan 10 '13 at 16:55
    
I've added additional detail. –  MgSam Jan 10 '13 at 17:00
    
RunWithElevatedPriveleges() should not be used to bypass SP security. It is intended to be used to make network calls as the application pool identity, not to circumvent security. User impersonation with a token is the correct way to do this. –  RJ Cuthbertson Jan 10 '13 at 19:37
add comment

1 Answer 1

up vote 1 down vote accepted

In order to properly use RunWithElevatedPrivileges(), you need to move the new SPSite() call inside the elevated block. otherwise it will get the SPSite reference using the ID of the user instead of the App Pool ID.

from Microsoft: "An SPSite object created outside the delegate can be referenced inside the delegate, however, the methods and property assessors of the object run with the privileges of the user context in which the objects were created, not with the elevated privileges."

share|improve this answer
    
Ah, ok. I remember why I wasn't doing this. I need the URL of the site collection not hard coded, which I was getting from SPContext.Current.Site.Url. This is null when you're inside of a RunWithElevatedPrivileges block. However, I realized I can just capture the URL outside of the block first. Thanks. –  MgSam Jan 10 '13 at 18:39
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.