0
votes

I need to check whether a particular user has access to a site/subsite in SharePoint programmatically.

Note: login user can have acces to few sites in my SharePoint site. So I have to show sites only to which the user have permission.

I used:

   using (SPWeb web = new SPSite(url).OpenWeb())
                {
                    SPWebCollection Sites = web.Webs;

                    foreach (SPWeb website in Sites)
                    {
                        SPUser loginUser = website.CurrentUser;
                        string username = loginUser.Name;
                        if (!website.IsRootWeb)
                        {
                            SPWebCollection subsites = website.Webs;
                            foreach (SPWeb supersubsite in subsites)
                            {

                                SPWebCollection thirdlevelsites = supersubsite.Webs;
                                foreach (SPWeb thirdlevel in thirdlevelsites)
                                {

thirdlevel.Site.CatchAccessDeniedException = false;
                                bool check = thirdlevel.DoesUserHavePermissions(SPContext.Current.Web.CurrentUser.LoginName, SPBasePermissions.Open);
                                if (check)
                                {
                                }
                                thirdlevel.Site.CatchAccessDeniedException = true;                                   
                                }

                            }
                        }
                    }
                }

but getting error at

bool check = thirdlevel.DoesUserHavePermissions(SPContext.Current.Web.CurrentUser.LoginName, SPBasePermissions.Open);

as :

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

1
Are you trying to list all the sites and subsites an user has access to? Please elaborate a bit.Ken
Yup.. I have multiple users. Few users have access to all sites and few not.I need to check the permission of the user to the current site before display. So I should not display the sites to which the login user doesnot have the access. For this approach I tried the above mention code but getting the error.karthik k

1 Answers

2
votes

If you're working with a Publishing Site, you should rely on the PortalSiteMapProvider (CombinedNavSiteMapProvider, CurrentNavSiteMapProvider, GlobalNavSiteMapProvider, WebSiteMapProvider, etc depending on your navigation needs) as this one is already fully security wise trimmed and you'll be able to traverse the complete tree with the best performance.

Otherwise, you should use the GetSubwebsForCurrentUser() on your SPWeb object, this method will only return sub web(s) accessible for the current user.

Hope it will help.