简体   繁体   中英

User permission check for a particular site in SharePoint

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))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM