14

I have given read only permisisons to a group of users. So they have no access to see listitem or any list.

I have create an application page with SPGridview which binds the listitems in question.

This page can be accessed by this group.

The problem is that when I write code with supertoken like this:

SPSite SiteInUserContext = SPContext.Current.Site;
SPWeb webInUserContext = SPContext.Current.Web;
Guid webGuid = webInUserContext.ID;
Guid siteGuid = SiteInUserContext.ID;
var user = webInUserContext.AllUsers[@"SHAREPOINT\SYSTEM"];
var superToken = user.UserToken;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
   using (SPSite site = new SPSite(siteGuid, superToken))
   { 
       //my code
   }
});

it's throwing an access denied of login User.

But when I write below code :

SPSite SiteInUserContext = SPContext.Current.Site;
SPWeb webInUserContext = SPContext.Current.Web;
Guid webGuid = webInUserContext.ID;
Guid siteGuid = SiteInUserContext.ID;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(siteGuid)
    {  
        //my code
    }
});

user are able to access this page with Gridview as well as also edit and add new listitems.

My doubt is in which situations we shoud use SuperUserToken with SPSecurity.RunWithElevatedPrivileges in Sharepoint object model.

6 Answers 6

21

The usual recommendations for using RWEP are to

  • Avoid using SPSecurity.RunwithElevatedPrivilege to access the SharePoint object model. Instead, use the SPUserToken to impersonate with SPSite.
  • Only use SPSecurity.RunwithElevatedPrivilege to make network calls under the application pool identity. Don't use it for elevation of privilege of SharePoint objects.
  • Never use elevated privilege to bypass security-- always use it to work with security.

Unlike your sample, if you pass the system user token to your SPSite constructor, you don't have to wrap it in a RunWithElevatedPrivileges you directly use it as :

SPUserToken systemAccountUserToken = SPContext.Current.Site.SystemAccount.UserToken;
using (SPSite elevatedSite =new SPSite("your-site-collection-URL",systemAccountUserToken)) {}

The user who will run that code will need to have at least "read" access ("visitor group") to your site collection as anonymous users are not allowed to retrieve the system token (without using the app pool account through RWEP...)

So to keep things short, use SPSecurity.RunWithElevatedPrivileges when you want to run some part of the code under the application pool account, remembering that it might not have all required permissions that you're expecting and run under the context of another user when you want to execute part of the code under another identity.

Hope it helped.

3
4

Check this out for when and how to use SPUserToken and SPSecurity.RunWithElevatedPrivileges.

Impersonation in SharePoint : An Extreme Overview

2
  • The link really shares good insight into the topic.
    – Amit
    Aug 16, 2014 at 8:42
  • 1
    Link is dead...
    – Jussi Palo
    Dec 7, 2016 at 10:04
1

To my knowledge the effect should be the same if used corectly. SPSecurity.RunWithElevatedPrivileges always run as if the Application Pool (with Full Control across all site collections in the Web App) is used, wheres you use the Token based variant for impersonation scenarios, even with other accounts. In your 1st code example it seems a little over-complicated, use it like this:

SPUserToken systoken = tempSite.SystemAccount.UserToken;

using (SPSite site = new SPSite(siteStr, systoken))
{
   using (SPWeb web = site.OpenWeb())
   {
       //right now, logged in as Site System Account
       Console.WriteLine("Currently logged in as: " +
                        web.CurrentUser.ToString());

       //add your code here
   }
}
3
  • Incorrect; RunWithElevated always runs as the app pool account
    – tarjeieo
    May 16, 2012 at 7:51
  • ... or correct if the app pool account is the system account, which is all but not recommended :) May 16, 2012 at 11:17
  • Thank you guys, I've updated the sentence, what i meant is more of the Full Control across site collections on that web. May 16, 2012 at 18:52
1

Best article to know all ways of using RunWithElevatedPrivileges. It is a lengthy article so I am unable to copy it here. It explains best practices and when and why you should use it.

http://sharepointquicksolutions.blogspot.in/2012/11/all-ways-of-runwithelevatedprivileges.html

1

To build on the answer given by Francois Verbeeck, I avoid using RunWithElevatedPrivileges unless I need to retrieve the SPUserToken for the system account.

Here is the method I use to retrieve the SPUserToken for the system account.

public static SPUserToken GetSystemToken(SPSite site) {
    bool cade = SPSecurity.CatchAccessDeniedException;
    SPSecurity.CatchAccessDeniedException = false;
    SPUserToken token = null;
    try {
        token = site.SystemAccount.UserToken;
    }
    catch (UnauthorizedAccessException) {
        SPSecurity.RunWithElevatedPrivileges(delegate() {
            using (SPSite elevatedSite = new SPSite(site.ID)) {
                token = elevatedSite.SystemAccount.UserToken;
            }
        });
    }
    finally {
        SPSecurity.CatchAccessDeniedException = cade;
    }
    return token;
}

Once I have the SPUserToken for the system account, here is the code pattern I use to impersonate the system account.

SPContext context = SPContext.Current;
SPSite contextSite = context.Site;
SPWeb contextWeb = context.Web;
using (SPSite site = new SPSite(contextSite.ID, GetSystemToken(contextSite))) {
    using (SPWeb web = site.OpenWeb(contextWeb.ID)) {
        // Do real work here
    }
}

Note: The code pattern above can be used to impersonate any account by replacing GetSystemToken(contextSite) with the appropriate SPUserToken.

1
  • thank you , this was really what i need which works without giving read access to Authenticated users on site collection
    – Iman
    Mar 7, 2015 at 7:01
0

Just to make it easier for people who will arrive at this post later, I basically have this piece of code that comes handy:

public static class SPWebExtensions {
  public static void RunWithElevatedPrivileges(this SPWeb web, Action<SPSite, SPWeb> codeToRunElevated) {
    if (CheckIfElevated(web)) {
      codeToRunElevated(web.Site, web);
    }
    else {
      using (var elevatedSite = new SPSite(web.Site.ID, SPUserToken.SystemAccount)) {
        using (var elevatedWeb = elevatedSite.OpenWeb(web.ID)) {
          codeToRunElevated(elevatedSite, elevatedWeb);
        }
      }
    }
  }
}

If you have a SPWeb object, to use this you just need to write:

web.RunWithElevatedPrivileges((elevatedSite, elevatedWeb) => {
  // your code goes here
}

and it will take care of all the plumbing, you can extend it in case you need special cleanup / exception handling.

instead of SPUserToken.SystemAccount there are other possibilities for example you can use web.AllUsers["SHAREPOINT\\system"].UserToken which will be very similar to calling SPSecurity.RunWithElevatedPreviledges but without impersonation. and finally what is the CheckIfElevated? well that depends on which user token you're going to use for example it can be: private static bool CheckIfElevated(SPWeb web) { return web.CurrentUser.LoginName == "SHAREPOINT\system"; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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