If you need to find out if the user is a member of any AD group, you will need to use the SID of the group if the user is not a "direct" member of the group (i.e. the user is a member of a nested group, which itself is a member of the "desired" AD groups).
(I have used this for many years, but have long lost the link to where I found it. I believe that there is actually an easier way to test nested groups in DirectoryServices 4.0, but I have not used it).
If you are using .NET 3.5 (as indicated in the link from Travis), you can verify the user credentials as follows:
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain) { if (pc.ValidateCredentials(username, password)) { } }
If you are not using .NET 3.5, you can still verify the credentials as follows:
var user = new DirectoryEntry("", username, password) try { user.RefreshCache(); } catch (DirectoryServicesCOMException ex) { } finally { user.Close(); }
Then, to verify AD group membership, use the following:
var user = new DirectoryEntry("", username, password); var searcher = new DirectorySearcher(); searcher.Filter = "(&(objectCategory=group)(samAccountName=" + YourGroupName + "))"; var group = searcher.FindOne(); if (group != null && IsMember(group.GetDirectoryEntry(), user))
IsMember Helper Method:
static bool IsMember(DirectoryEntry group, DirectoryEntry user) { group.RefreshCache(new string[] { "objectSid" }); SecurityIdentifier groupSID = new SecurityIdentifier((byte[])group.Properties["objectSid"].Value, 0); IdentityReferenceCollection refCol; user.RefreshCache(new string[] { "tokenGroups" }); IdentityReferenceCollection irc = new IdentityReferenceCollection(); foreach (byte[] sidBytes in user.Properties["tokenGroups"]) { irc.Add(new SecurityIdentifier(sidBytes, 0)); } refCol = irc.Translate(typeof(NTAccount)); PropertyValueCollection props = user.Properties["tokenGroups"]; foreach (byte[] sidBytes in props) { SecurityIdentifier currentUserSID = new SecurityIdentifier(sidBytes, 0); if (currentUserSID.Equals(groupSID)) { return true; } } return false; }