Wednesday, October 31, 2007

SharePoint: Does the user have permissions?

A common task in SharePoint programming is writing security code. One of the great things about the object model is that it is security trimmed, so you can usually just ask for items that the user has permissions for. However, there may be items that the user can access but the user still doesn't have access to perform a specific task-- which is a great reason to check for permissions before attempting an operation. I'm pretty sure I've blogged about this before... but I've heard this question several times lately.
To check for permissions on an item, the SPSecurableItem interface defines 2 methods for checking security. The DoesUserHavePermissions method returns a bool speccifying if the user can access the item, where the CheckUserHasPermissions method will throw a security exception, which causes a 401 http status if the current SPSite's CatchAccessDeniedException property isn't set to false. Also note that you call these using the SPBasePermissions value which specifies the task you want to check permissions for-- and you don't use the overloaf
The following sample shows how to check permissions on the SPWeb level:
SPWeb web = SPContext.Current.Web ;if (web.DoesUserHavePermissions(SPBasePermissions.ViewListItems){ // do something, like Enumerate lists}
The SPList is also an ISecurableObject, which means that you can apply the same principlesto check permissions on lists. To check the user’s permission to view list items within aspecific list, call the list’s DoesUserHavePermissions method as follows:foreach(SPList list in web.lists){ if (list.DoesUserHavePermissions(SPBasePermissions.ViewListItems)) { /* Process the list */ }}
Likewise, the same method is available in other objects, such as the SPListItem class, whichcan be used to ensure that the user has permissions to the item or document:foreach(SPListItem item in list.Items){ if (item.DoesUserHavePermissions(SPBasePermissions.ViewListItems)) { {/* Process the list item */ } }
You can also check if the anonymous user has access to an item like this, in the case where the current user is anonymous:if ((list.AnonymousPermMask64 & SPBasePermissions.ViewListItems) == SPBasePermissions.ViewListItems)
{ // Do something here... }
You can also get the subwebs for the calling user using the method, which will return a security trimmed collection of webs:
SPContext.Current.Web.GetSubwebsForCurrentUser();

No comments: