Test With Correct Privileges

When developing web parts and other components with code, it's important to remember that operations performed by code may require certain privileges.  During development, the code runs in the security context of the developer, who is usually a server administrator.  This means all operations are permitted, so access problems don't arise.  During testing and production, however, the security context of the code may be different because it's being invoked by testers and end-users.

Therefore, all components should be tested with several end-user accounts: one would be the developer’s account which is usually a server admin; that’s how most people do their unit testing. But tests should also be made with an account of minimal privilege, say Visitor.  Some components might be doing things with the object model that will only work when an administrator invokes it. If this turns out to be the case, a technique called “elevation of privilege” can be used to overcome it.  See MSDN article Running Commands with Elevated Privileges in Windows SharePoint Services 3.0 for an explanation of doing this.

What code needs to be tested using different privileges?

1. Code that's invoked as the result of an end-user action. An example is a custom web part that is displayed on a page. The end-user opens the page and this is what invokes the web part code under the user's security context. A counter-example is timer job code that is invoked by SharePoint.

2. Code that uses the SharePoint API. This is typically where security errors arise. If a component does not use the SharePoint API, then chances are it will not need to elevate its privilege. To be entirely sure, it should be tested at minimum privilege, but this criterion can be used to prioritize testing of other components higher.

How can a developer test with different accounts?

The simplest approach is to create three accounts "Test Visitor," "Test Member," and "Test Owner" in Active Directory and then to add these accounts to matching groups on the test sites.

First, the developer must decide in what security contexts the component is supposed to work. For example, most end-user web parts should work for users signed on as Test Visitor. On the other hand, an stsadm extension is only invoked by a server admin and should not be tested with a minimum privilege account.

"Sign on as different user" can be used to choose one of the test accounts as appropriate; however, in some cases, this approach does not seem to “stick” based on browser state or browsing behavior (e.g. browsing to My Site when browser is configured for automatic logon). The best way to ensure that the desired account is used is to configure the browser to always prompt for credentials, then to open a new browser window to begin testing. Then, re-run all unit tests that exercise the component directly (not, say, the deployment of the component).

Skip to main content