WSS promotion code execution privileges

WSS promotion code execution privileges

Overview:

WSS use impersonation to execute code that is executed Code Access Web Part or custom application using the current user logged by default. In most cases, this mechanism can accurately and strictly control the standard user permissions his access to specific website resources and sensitive data, which is the goal we want to achieve.

Sometimes, however, in some special scenes, your code must be executed wss target certain methods restricted, even if the requester is not the privilege of the user. So in this case, we need to elevate privileges ordinary users to execute code.

Implementation:

SPSecurity.RunWithElevatedPrivileges(delegate()

{

    // code that requires elevated permissions to execute

});

Case Study:

Gets the name of the site collection owner SPSite.Owner.Name

The default is the user need site collection administrator privileges can get, if not execute code with elevated privileges to an ordinary user to execute SPSite.Owner.Name, the system reported an error "Access Denied".

However, the following code is executed, our ordinary user privileges, can successfully get access to SPSite.Owner.Name

SPSite siteColl = SPContext.Current.Site;

SPWeb site = SPContext.Current.Web;

SPSecurity.RunWithElevatedPrivileges(delegate() {

using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID)) {

using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID))

{

        // Run as SHAREPOINT "System account system account identity

      string SiteCollectionOwner = ElevatedsiteColl.Owner.Name;    

    }

 }

});

note:

SPSecurity.RunWithElevatedPrivileges using elevated privileges inside the code, must instantiate SPSite, SPWeb object, and the object can not be used to obtain Microsoft.SharePoint.SPContext.Current property, because those objects is based on the current user's security context created

Please use using instantiate an object, so that the system can automatically perform Dispose, complete release of resources.

This way mentioned above is the highest administrator account full permissions to execute code, of course, we can also specify the account running the code:

SPSite siteColl = SPContext.Current.Site;

SPWeb site = SPContext.Current.Web;

SPUser user = site.Users[@"litware\ken"];

SPUserToken userToken = user.UserToken;

 

SPSecurity.RunWithElevatedPrivileges(delegate() {

using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID, userToken)) {

using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID))

{// to litware "ken run the
      string SiteCollectionOwner = ElevatedsiteColl.Owner.Name;    

    }

 }

});

In this way, then, the code to "ken of litware permission to run, no matter ken authority is high or low.

Reproduced in: https: //www.cnblogs.com/llbofchina/archive/2008/05/24/1206393.html

Guess you like

Origin blog.csdn.net/weixin_33901926/article/details/94206508