Friday, August 28, 2009

Running Code with Elevated Permissions

 

There are 2 ways to run code under elevated permissions. The first one is using the token created from SharePoint\System(internal user) user

public static SPWeb GetElevatedWeb
        {
            get
            {
                var superUser = SPContext.Current.Web.AllUsers[@"SHAREPOINT\SYSTEM"];
                var superToken = superUser.UserToken;
                using (var site = new SPSite(SPContext.Current.Web.Url, superToken))
                {
                    return site.RootWeb;
                }
            }
        }

This function returns a SPWeb object which is created using elevated permissions

The second method is using SPSecurity.RunWithElevatedPrivileges

public static SPWeb GetSPElevatedWeb
        {
            get
            {
                SPWeb web = null;
                string siteURL = SPContext.Current.Site.Url;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPSite objSite = new SPSite(siteURL);
                    web = objSite.OpenWeb();
                });
                return web;
            }
        }

The SPSite object is created by reading the SPContext object before calling RunWithElevatedPrivileges as the context will change in the code block

3 comments:

Anonymous said...

Your blog keeps getting better and better! Your older articles are not as good as newer ones you have a lot more creativity and originality now. Keep it up!
And according to this article, I totally agree with your opinion, but only this time! :)

Anonymous said...

You have really great taste on catch article titles, even when you are not interested in this topic you push to read it

Anonymous said...

What a great web log. I spend hours on the net reading blogs, about tons of various subjects. I have to first of all give praise to whoever created your theme and second of all to you for writing what i can only describe as an fabulous article. I honestly believe there is a skill to writing articles that only very few posses and honestly you got it. The combining of demonstrative and upper-class content is by all odds super rare with the astronomic amount of blogs on the cyberspace.