Blogger Widgets
  • Sharing Photos using SignalR
  • TFS Extenstion - allows copy work items between projects
  • Displaying jquery progressbar with ajax call on a modal dialog
  • Managing windows services of a server via a website
  • Exploring technologies available to date. TechCipher is one place that any professional would like to visit, either to get an overview or to have better understanding.

Search This Blog

Tuesday, 4 December 2012

Find if user is member of Active Directory Group C#

Finding out if user is a member of Active Directory Group can be done using following snippet of code

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

2 comments:

Copyright © 2013 Template Doctor . Designed by Malith Madushanka - Cool Blogger Tutorials | Code by CBT | Images by by HQ Wallpapers