Active Directory: Retrieve User information

前端 未结 5 1037
温柔的废话
温柔的废话 2020-12-13 11:30

I\'ve got a web application that is running against Windows Authentication using our Active Directory. I\'ve got a new requirement to pull some personal information through

5条回答
  •  独厮守ぢ
    2020-12-13 12:10

    You might find the following snippet useful as a starter.

    public static bool IsUserInGroup(string lanid, string group)
    {
        DirectoryEntry entry = new DirectoryEntry("LDAP://" + LDAPPATH);
        if(entry != null)
        {
            entry.Username=@"LDAPUSER";
            entry.Password="LDAPPASSWORD";
            DirectorySearcher srch = new DirectorySearcher(entry);
            srch.Filter = String.Format("(&(objectClass=person)(sAMAccountName={0}))", lanid);
            srch.PropertiesToLoad.Add("memberOf");
    
            SearchResult result = srch.FindOne();
            if(result != null)
            {
                if(result.Properties.Contains("memberOf"))
                {
                    string lookfor = String.Format("cn={0},", group.ToLower());
                    foreach(string memberOf in result.Properties["memberOf"])
                    {
                        if(memberOf.ToLower().StartsWith(lookfor))
                            return true;
                    }
                }
            }
            return false;
        }
        throw new Exception(String.Format("Could not get Directory lanid:{0}, group{1}",   lanid, group));
    }
    

提交回复
热议问题