Custom Method for Checking Permissions on a SPWeb Object
by liquidpooled on Nov.21, 2008, under .NET, Microsoft, Office, Sharepoint Server, TechNet, Visual Studio 2005, Visual Studio 2008, Windows SharePoint Services
The out-of-the-box method DoesUserHavePermissions() on an SPWeb object does not take indirect membership into account (i.e. the current user is a member of a domain group that has access the the SPWeb being checked). To get around this, I use the following method (DoesUserHavePermssionsToWeb(SPUser, SPWeb)):
private bool DoesUserHavePermssionsToWeb(ref SPUser user, ref SPWeb web)
{
bool hasPermission = false;
SPBasePermissions perms = this.GetPermissionsForUser(ref user, ref web);
if (perms.ToString().Contains(SPBasePermissions.Open.ToString())
|| perms.ToString().Contains(SPBasePermissions.FullMask.ToString()))
hasPermission = true;
if (!hasPermission)
{
// Check the users groups - this is for indirect membership;
foreach (string groupLoginName in this.GetCurrentUserADGroups())
{
try
{
SPUser groupUser = web.SiteUsers[groupLoginName];
perms = this.GetPermissionsForUser(ref groupUser, ref web);
if (perms.ToString().Contains(SPBasePermissions.Open.ToString())
|| perms.ToString().Contains(SPBasePermissions.FullMask.ToString()))
{
hasPermission = true;
break;
}
}
catch { }
}
}
return hasPermission;
}
private SPBasePermissions GetPermissionsForUser(ref SPUser user, ref SPWeb web)
{
SPBasePermissions perms = SPBasePermissions.EmptyMask;
try
{
SPUserToken userToken = user.UserToken;
System.Reflection.MethodInfo getPermissions = typeof(Microsoft.SharePoint.Utilities.SPUtility).GetMethod("GetPermissions",
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.InvokeMethod |
System.Reflection.BindingFlags.Static);
perms = (SPBasePermissions)getPermissions.Invoke(null, new object[] { userToken, web });
}
catch { }
return perms;
}
private System.Collections.ArrayList GetCurrentUserADGroups()
{
// Get the current groups for the logged in user;
System.Collections.ArrayList groups = new System.Collections.ArrayList();
foreach (System.Security.Principal.IdentityReference group in System.Web.HttpContext.Current.Request.LogonUserIdentity.Groups)
{
groups.Add(group.Translate(typeof (System.Security.Principal.NTAccount)).ToString());
}
return groups;
}
Note that in the above method is checking for SPBasePermissions of Open and FullMask.
The supporting methods are also included. After checking the permissions on the web object for the current logged in user, if not permissions have been granted we continue to check each Active Directory group that the current user is a member of.