Method 1: using PrincipalContext
public static bool IsGroupMember(string domain, string group, string login) { bool result = false; PrincipalContext context = new PrincipalContext(ContextType.Domain, domain); UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(context, login); GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(context, group); if (userPrincipal != null) { if (userPrincipal.IsMemberOf(groupPrincipal)) { result = true; } } return result; }Note: This is easy to use but only works based on specific domain
Method 2:using DirectoryEntry
public static bool IsGroupMember(Logger logger, string group, string userName) { string strSid; bool result = false; clsLookupAccountName.GetAccountSid(userName, out strSid); DirectoryEntry rootDSE = new DirectoryEntry("GC://RootDSE"); string rootDomainNamingContext = rootDSE.Properties["rootDomainNamingContext"].Value.ToString(); string filter = "(&(objectCategory=user)(objectSid=" + strSid + "))"; DirectorySearcher searcher = new DirectorySearcher("GC://" + rootDomainNamingContext); searcher.Filter = filter; searcher.PropertiesToLoad.Clear(); searcher.PropertiesToLoad.Add("distinguishedName"); SearchResult sr = searcher.FindOne(); string userDN = sr.Properties["distinguishedName"][0].ToString(); DirectoryEntry groupEntry = new DirectoryEntry(group); PropertyValueCollection pvc = groupEntry.Properties["member"]; result = pvc.Contains(userDN); return result; }Note: This requires you to understand AD objects and its properties. Allows you to search universally
It has become appallingly obvious that our technology has exceeded our humanity. Albert Einstein
I find your blog cool. Please continue making things like this...
ReplyDeleteGreat Article
ReplyDeleteASP.NET MVC Training
Online MVC Training
Online MVC Training India
Dot Net Training in Chennai
.Net Online Training
.net training online
Dot Net Online Training