Daniel Larson’s Best Practices for Elevated Privilege in SharePoint

[via Daniel Larson]

Daniel Larson, a MOSS MVP, has been ranting over the past few days about the use of the SPSecurity.RunWithElevatedPrivileges method. While I have been amused with his rants, I share his concerns and frustrations as a result of using the method in my SharePoint development experience and seeing the method abused and missused in many code reviews. Today, he posted a list of his best practices for gaining “elevated privileges” SharePoint.

Daniel Larson’s list of best practives for elevated privileges in SharePoint:

  • Avoid using SPSecurity.RunwithElevatedPrivilege to access the SharePoint object model. Instead, use the SPUserToken to impersonate with SPSite.
  • If you do use SPSecurity.RunwithElevatedPrivilege, dispose of all objects in the delegate. Do not pass SharePoint objects out of the RunwithElevatedPrivilege  method.
  • Only use SPSecurity.RunwithElevatedPrivilege to make network calls under the application pool identity. Don’t use it for elevation of privilege of SharePoint objects.
  • Always use the SPSite constructor with an SPUserToken to create an elevated privilege security context in SharePoint. To impersonate the system, use the SystemAccount.UserToken property of the current SPSite context, such as:
    var site = new SPSite(SPContext.Current.Site.ID,  SPContext.Current.Site.SystemAccount.UserToken);
  • Avoid passing SharePoint objects between different security contexts (SPSite instances), with the exception of the SPUserToken used in the SPSite ctor. An SPUser object created from SPSite A cannot (reliably) be passed to SPSite B. This can be the source of obscure bugs in production that are difficult to reproduce in development. For example, an SPUser reference created from SPContext.Current.Site cannot reliably be used in an elevated site context, as the user reference may take on a different meaning in the alternate context.
  • Never use elevated privilege to bypass security– always use it to work with security.
  • Restrict what assemblies can use elevated privilege by running in minimal trust, avoiding the GAC, and auditing any CAS policies deployed with vendor solutions.

Leave a Reply