2
votes

What is the best way to check if a user has permission to a site collection/site? I'm currently using the following

   SPSecurity.RunWithElevatedPrivileges(
       () => {using (var site = new SPSite(nodeUrl))
                     {
                         using (var web = site.OpenWeb())
                         {
                             retValue=
                                 web.DoesUserHavePermissions(
                                     context.User.Identity.Name,
                                     SPBasePermissions.Open);
                         }
                     }
             });

This doesn't seem to be working properly. If the user was never added to the site this works. But if the user was added and then removed DoesUserHavePermission(.. SPBasePermission.Open) still returns true, but when the user tries to access the site SharePoint throws the access denied page.

After a little more digging I found that the user account is still in the web.AllUsers list, but it has no Roles assigned.

3
Running into a similar issue with users in ad groups. Adding/removing users is not having an effect on permission checking through the API.. - markt

3 Answers

3
votes

Use CheckPermissions instead of DoesUserHavePermissions. See the SPWeb.CheckPermissions Method .

1
votes

I perform a similar check (looping over a list of workspaces checking for permissions), here is the relevant bit of code I use:

string LoginName = SPContext.Current.Web.CurrentUser.LoginName
bool permission = web.DoesUserHavePermissions(LoginName, SPBasePermissions.Open)
0
votes

I think you are on the right track

The SP User is member of the SiteCollection (Site) and not the Web in particular.

you need to check agains the Site.RootWeb

also from your code, I think you don't get the actual Context

SPContext.Current would be the correct context

 SPSecurity.RunWithElevatedPrivileges(
   () => {using (var site = new SPSite(nodeUrl))
                 {
                     using (var web = site.OpenWeb())
                     {
                         retValue=
                             web.DoesUserHavePermissions(
                                 context.User.Identity.Name,
                                 SPBasePermissions.Open);
                     }
                 }
         });

Best of luck