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 given permission only read only to Users Group.so there are not access to see listitem or any list.

i have create application page with SPGridview with bind listitem.

this page access by this Group.

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
                }
            });

its throwing 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 can able to access this page with Gridview as well as also edit,add new item in to listitem.

My doubt is in Which Situation We use SuperUserToken with SPSecurity.RunWithElevatedPrivileges in Sharepoint object model.

share|improve this question

6 Answers 6

up vote 14 down vote accepted

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.

share|improve this answer
    
Great answer! You should use SPUserToken.SystemAccount instead (see msdn.microsoft.com/en-us/library/…). –  Bernd Rickenberg Oct 29 '13 at 12:07
    
What does RWEP stand for? –  jobin Apr 1 at 15:41
    
@jobin : Run With Elevated Privileges (RWEP) –  Francois Verbeeck Apr 2 at 9:17

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

Impersonation in SharePoint : An Extreme Overview

share|improve this answer
    
nice blog.thanks for sharing!!! –  Jigs Jun 3 '12 at 17:19
    
The link really shares good insight into the topic. –  Sane.Amit Aug 16 '14 at 8:42

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
   }
}
share|improve this answer
    
Incorrect; RunWithElevated always runs as the app pool account –  tarjeieo May 16 '12 at 7:51
    
... or correct if the app pool account is the system account, which is all but not recommended :) –  Francois Verbeeck May 16 '12 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. –  C. Marius - MVP May 16 '12 at 18:52

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

share|improve this answer

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.

share|improve this answer
    
thank you , this was really what i need which works without giving read access to Authenticated users on site collection –  imanabidi Mar 7 at 7:01

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"; }

share|improve this answer

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.