• Aras学习笔记 (12) C#代码读取域用户列表(转,翻译)


    Introduction 

    This tip describes how to list Active Directory users.  介绍如何提取AD域中的用户列表

    Using the Code 

    The below code demonstrates how can we fetch Active Directory (AD) using Directory Service. For this, I'm using object array (Users) and here is the structure:

    首先创建实体类,用户保存用户信息。

    public class Users
    {
        public string Email { get; set; }
        public string UserName { get; set; }
        public string DisplayName { get; set; }
        public bool isMapped { get; set; }
    }

    The code below shows how to fetch user information from Active Directory.

    以下代码为如何AD域中的用户信息。

    public List<Users> GetADUsers()
    {
        try
        {
            List<Users> lstADUsers = new List<Users>();  //定义返回列表
            string DomainPath = "LDAP://DC=xxxx,DC=com" //改为自己公司的LDAP访问地址
            DirectoryEntry searchRoot = new DirectoryEntry(DomainPath); 
            DirectorySearcher search = new DirectorySearcher(searchRoot);
            search.Filter = "(&(objectClass=user)(objectCategory=person))";
            search.PropertiesToLoad.Add("samaccountname");  //提取samaccountname,mail,usergroup和displayname四个字段
            search.PropertiesToLoad.Add("mail");
            search.PropertiesToLoad.Add("usergroup");
            search.PropertiesToLoad.Add("displayname");//first name
            SearchResult result;
            SearchResultCollection resultCol = search.FindAll();  //执行查询
            if (resultCol != null)
            {
                for (int counter = 0; counter < resultCol.Count; counter++)  //循环读取
                {
                    string UserNameEmailString = string.Empty;
                    result = resultCol[counter];
                    if (result.Properties.Contains("samaccountname") && 
                             result.Properties.Contains("mail") && 
                        result.Properties.Contains("displayname"))
                    {
                        Users objSurveyUsers = new Users();
                        objSurveyUsers.Email = (String)result.Properties["mail"][0] + 
                          "^" + (String)result.Properties["displayname"][0];
                        objSurveyUsers.UserName = (String)result.Properties["samaccountname"][0];
                        objSurveyUsers.DisplayName = (String)result.Properties["displayname"][0];
                        lstADUsers.Add(objSurveyUsers);
                    }
                }
            }
            return lstADUsers;  //返回
        }
        catch (Exception ex)
        {
     
    }
     

    Let's see what is happening here... 实现原理介绍

    The DirectoryEntry class encapsulates an object in Active Directory Domain Services, DirectoryEntry(DomainPath) initializes a new instance of the class that binds this instance to the node in Active Directory Domain Services located at the specified path, i.e., DomainPath.

    In DirectorySearcher, create a DirectorySearcher object which searches for all users in a domain. search.Filter = "(&(objectClass=user)(objectCategory=person))" filters the search.

    The search filter syntax looks a bit complicated, but basically it filters the search results to only include users - "objectCategory=person" and "objectClass=user" - and excludes disabled user accounts by performing a bitwise AND of the userAccountControl flags and the "account disabled" flag.

    NoteSAMAccountName is unique and also indexed. sAMAccountName must be unique among all security principal objects within the domain.

    search.FindAll(); retrieves all the elements that match the conditions defined.

    Let's see how we get the current login user.

    //获取当前登录域用户

    public string GetCurrentUser()
    {
        try
        {
            string userName = HttpContext.Current.User.Identity.Name.Split('\')[1].ToString();
            string displayName = GetAllADUsers().Where(x => 
              x.UserName == userName).Select(x => x.DisplayName).First();
            return displayName;
        }
        catch (Exception ex)
        { //Exception logic here 
        }
    }
     

    Let's see what this code snippet does:

    • HttpContext.Current.User.Identity returns the Windows identity object including AuthenticationType ("ntml", "kerberos" etc..), IsAuthenticatedName ("Domain/username").
    • HttpContext.Current.User.Identity.Name returns "Domain\username" .

    Hope this helps you understand how directory service works with AD. //感谢原作者大神

  • 相关阅读:
    096实战 在windows下新建maven项目
    095实战 ETL的数据来源,处理,保存
    094实战 关于js SDK的程序,java SDK的程序
    093实战 Nginx日志切割,以及脚本上传nginx的切割日志
    092实战 数据收集(各种事件)
    091实战 Nginx配置(日志服务器中关于日志的产生)
    android64位机子兼容32位.so库文件
    给 Android 初学者的 Gradle 知识普及
    Android重力感应开发
    随笔之Android平台上的进程调度探讨
  • 原文地址:https://www.cnblogs.com/61007257Steven/p/10007397.html
Copyright © 2020-2023  润新知