I have the requirement to enumerate a list of users that are in an Active Directory group that has been granted rights to an SPWeb. If the site collection is using windows auth this is no problem and you can get user list via a simple call to SPUtility.GetPrincipalsInGroup. However when it's using claims this is where this method breaks. My question is, is it possible to utilize the SharePoint API to get user list from an Active Directory group when the site collection is configured with Claims auth?
2 Answers
Claims authentication combines different authentication methods like basic, active directory etc. This means that the group that has been granted rights to an SPWeb does not necessarily has to be an Active Directory group.
After a related Stack Overflow answer mentioned the System.DirectoryServices.AccountManagement namespace, I tried using it in my SharePoint site that includes Claims Authentication to determine if a username is a member of an Active Directory security group on the domain. It worked.
public bool UserIsMemberOf(string userNameWithoutDomain, string domainName, string groupName) {
var result = false;
SPSecurity.RunWithElevatedPrivileges(() => {
var context = new PrincipalContext(ContextType.Domain, domainName);
using (var searcher = new PrincipalSearcher()) {
searcher.QueryFilter = new GroupPrincipal(context, groupName);
var group = searcher.FindOne() as GroupPrincipal;
if (group != null) {
result = group.GetMembers().Any(x => string.Equals(userNameWithoutDomain, x.SamAccountName, StringComparison.InvariantCultureIgnoreCase));
}
}
});
return result;
}