Check User Permissions on a SharePoint Site using C#
Another SharePoint 2007 development post from the non developer, so feel free to offer any suggestions and comments around my code as I’m still learning. I know, I should be doing this on SharePoint 2010. Trust me, I’m trying to get us there.
Anyways, a brief background on what I’m trying to accomplish. I’m working on a navigation solution for our current intranet that queries a list of SharePoint sites that have been requested, approved and created via our site request process. The query results are then filter based on if the current user has access to the site. This list contains variety of sites, site collections and sub-sites that are spread out across 3 different web applications. The solution then displays those sites in a web part for users to have “quick access” to their collaboration sites. It’s basically a way to provide navigation (contained in a web part) across site collections and web applications automatically off a list of sites.
In order to check for access I decided to use the DoesUserHavePermissions() function. However, after writing this function:
private bool UserAccessToSite(String user, SPWeb testWeb, SPSite testSite){ bool access = false; try{ access = testWeb.DoesUserHavePermissions(user, SPBasePermissions.EmptyMask); return access; } catch{ access = false; return access; } }
I was getting the following error stating that the “List does not exist”
I tried a variety of different approaches just to get it to return false if the user has Access Denied to the site. After a bunch of different tries and some searching online, I ran across this post by Krichie that solved the problem for me.
Right before checking DoesUserHavePermissions I had to add the line SPSite.CatchAccessDeneidExceptoin=false;
So, the final code that is now working is:
private bool UserAccessToSite(String user, SPWeb testWeb, SPSite testSite){ bool access = false; try{ testSite.CatchAccessDeniedException = false; access = testWeb.DoesUserHavePermissions(user, SPBasePermissions.EmptyMask); return access; } catch{ access = false; return access; } }
My web part is now configured in order to query the list and only return a link to a SharePoint site if the user currently logged into SharePoint has access to that site. I still have some work to do on the web part and the rest of the solution, so as I continue this adventure I’ll try to post any other updates. Who knows, maybe once I finish it I’ll even post the whole solution up here.
Again, feel free to correct my code or offer other suggestions as I continue to delve into the SharePoint development space.