C# - 在活动目录中查找直接下属

本文关键字:查找 活动 | 更新日期: 2023-09-27 18:36:47

我正在使用System.DirectoryServices.AccountManagement来管理我的登录用户帐户。

我能够获取登录用户的信息,但无法获取基于经理的直接下属用户 ID。

var context = new PrincipalContext(ContextType.Domain);
var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);

我参考了这个链接: C# - 在活动目录中查找用户管理器

但仍然没有任何线索。有人可以帮助我吗?

C# - 在活动目录中查找直接下属

我设法找出了直接报告的目录属性("直接报告")。

只是添加一个新的目录属性,如下所示:

    // Create the "Direct Report" property.    
    [DirectoryProperty("directReports")]
    public List<string> DirectReports
    {
        get
        {
            var directReportsName = new List<string>();
            if (ExtensionGet("directReports").Length == 0)
                return directReportsName;
            for (int i = 0; i < ExtensionGet("directReports").Length; i++)
            {
                string userString = (string)ExtensionGet("directReports")[i];
                //example of userString = CN=name,OU=Users,OU=department,OU=AP,OU=Software,DC=company,DC=priv,DC=company,DC=com
                //split by comma
                var tempCN = userString.Split(',').First();
                var tempName = tempCN.Split('=');
                var userName= tempName[1];
                directReportsAlias.Add(userName);
            }
            return directReportsName;
        }
    }

我为活动目录搜索设计了类。

此类支持。

  1. 按相同帐户名称搜索员工
  2. 按员工 ID 搜索员工
  3. 按员工代码搜索员工
  4. 按员工电子邮件搜索员工
  5. 搜索员工管理
  6. 搜索团队成员

类代码

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
namespace UAT.COMMON
{
    #region RefranceHelpers
    /*
        //https://www.c-sharpcorner.com/article/active-directory-and-net/
        //https://ianatkinson.net/computing/adcsharp.htm
        //https://ianatkinson.net/computing/adcsharp.htm
    */
    #endregion
    public enum SearchBy
    {
        StartNTID=0,
    }
    public class ManageDirectoryServices : IDisposable
    {
        public ContextType contextType = ContextType.Domain;
        public PrincipalContext Context { get; protected set; }
        public UserPrincipal User { get; protected set; }
        public UserPrincipal Manager { get; protected set; }
        public bool IsManager { get; protected set; }
        public List<UserPrincipal> DirectReports { get; protected set; }
        public class AuthenticationResult
        {
            public AuthenticationResult()
            {
                IdentityError = new List<IdentityError>();
                IsSuccess = IdentityError.Count > 0;
            }
            public List<IdentityError> IdentityError { get; private set; }
            public String RoleName { get; private set; }
            public Boolean IsSuccess { get; set; }
            public ManageDirectoryServices Context { get; set; }
        }
        public ManageDirectoryServices()
        {
            Context = new PrincipalContext(contextType);
            DirectReports = new List<UserPrincipal>();
        }
        public ManageDirectoryServices(string ntid)
        {
            Context = new PrincipalContext(contextType);
            DirectReports = new List<UserPrincipal>();
            GetEmployeeByNTID(NormalizeNTID(ntid));
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ntid">This is SamAccountName</param>
        /// <returns></returns>
        public ManageDirectoryServices GetEmployeeByNTID(string ntid)
        {
            if (string.IsNullOrWhiteSpace(ntid)) return null;
            UserPrincipal searchTemplate = new UserPrincipal(Context)
            {
                SamAccountName = ntid
            };
            PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
            User = (UserPrincipal)ps.FindOne();
            return this;
        }

        public ManageDirectoryServices GetEmployee(string strSearch,string prop)
        {
            if (string.IsNullOrWhiteSpace(strSearch)) return this;
            if (string.IsNullOrWhiteSpace(prop)) return this;
            DirectorySearcher search = new DirectorySearcher();
            search.Filter = String.Format("(cn={0})", strSearch);
            search.PropertiesToLoad.Add(prop);
            var result = search.FindAll();
            if (result != null)
            {
                int directReports = result.Count; //result.Properties["displayname"].Count;
                if (directReports < 0) return null;
                for (int counter = 0; counter < directReports; counter++)
                {
                    var user = (string)result[counter].Properties["givenname"][counter];
                    var reporte = UserPrincipal.FindByIdentity(Context, IdentityType.DistinguishedName, user);
                    this.DirectReports.Add(reporte);
                    IsManager = true;
                }
                return this;
            }
            return null;
        }

        public ManageDirectoryServices GetEmployee(UserPrincipal searchTemplate)
        {
            if (searchTemplate == null) return null;
            PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
            User = (UserPrincipal)ps.FindOne();
            return this;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="NTID">This is SamAccountName</param>
        /// <returns></returns>
        public bool IsUserExist(string NTID)
        {
            var data = GetEmployeeByNTID(NormalizeNTID(NTID));
            return !string.IsNullOrWhiteSpace(data?.User?.SamAccountName);
        }
        public bool IsUserExist()
        {
            var data = User;
            return !string.IsNullOrWhiteSpace(data?.SamAccountName);
        }
        public ManageDirectoryServices GetEmployeeByEmail(string email)
        {
            if (string.IsNullOrWhiteSpace(email)) return null;
            UserPrincipal searchTemplate = new UserPrincipal(Context)
            {
                EmailAddress = email
            };
            PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
            User = (UserPrincipal)ps.FindOne();
            return this;
        }
        public ManageDirectoryServices GetEmployeeByEmpId(string employeeId)
        {
            if (string.IsNullOrWhiteSpace(employeeId)) return null;
            UserPrincipal searchTemplate = new UserPrincipal(Context)
            {
                EmployeeId = employeeId
            };
            PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
            User = (UserPrincipal)ps.FindOne();
            return this;
        }
        public ManageDirectoryServices GetManager()
        {
            if (this.User == null) return null;
            DirectoryEntry ManagerDE = this.User.GetUnderlyingObject() as DirectoryEntry;
            var manager = ManagerDE.Properties["manager"].Value.ToString();
            UserPrincipal oManager = UserPrincipal.FindByIdentity(Context, IdentityType.DistinguishedName, manager);
            this.Manager = oManager;
            return this;
        }
        public ManageDirectoryServices GetDirectReports()
        {
            if (this.User == null) return this;
            DirectorySearcher search = new DirectorySearcher();
            search.Filter = String.Format("(cn={0})", this.User.SamAccountName);
            search.PropertiesToLoad.Add("directReports");
            SearchResult result = search.FindOne();
            if (result != null)
            {
                int directReports = result.Properties["directReports"].Count;
                if (directReports < 0) return null;
                for (int counter = 0; counter < directReports; counter++)
                {
                    var user = (string)result.Properties["directReports"][counter];
                    var reporte = UserPrincipal.FindByIdentity(Context, IdentityType.DistinguishedName, user);
                    this.DirectReports.Add(reporte);
                    IsManager = true;
                }
                return this;
            }
            return null;
        }
        public string NormalizeNTID(string Id)
        {
            if (string.IsNullOrWhiteSpace(Id)) return "";
            return Id.Trim().ToUpper().Replace(@"'", "")
                .Replace("''", "")
                .Replace("/", "")
                .Replace("//", "")
                .Replace("MS", "")
                .Replace("MS//", "")
                .Replace("MS''", "");
        }
        public AuthenticationResult SignIn(string ntid, string password)
        {
            var NormalizeNTID = this.NormalizeNTID(ntid);
            bool IsAuthenticated = false;
            IdentityError identityError = new IdentityError();
            ManageDirectoryServices context = null;
            AuthenticationResult authenticationResult = new AuthenticationResult();
            var IsSuccess = Context.ValidateCredentials(NormalizeNTID, password, ContextOptions.Negotiate);
            context = GetEmployeeByNTID(NormalizeNTID);
            if (IsSuccess)
            {
                if (context.User != null)
                {
                    IsAuthenticated = true;
                    this.User = context.User;
                    authenticationResult.Context = context;
                    authenticationResult.IsSuccess = true;
                }
            }
            else
            {
                if (!IsAuthenticated || User == null)
                {
                    authenticationResult.IdentityError.Add(new IdentityError
                    {
                        Code = "InCorrectUserAndPassword",
                        Description = "Username or Password is not correct"
                    });
                }
                if (context.User.IsAccountLockedOut())
                {
                    authenticationResult.IdentityError.Add(new IdentityError
                    {
                        Code = "YourAccountIsLocked",
                        Description = "Your account is locked."
                    });
                }
                if (context.User.Enabled.HasValue && User.Enabled.Value == false)
                {
                    authenticationResult.IdentityError.Add(identityError = new IdentityError
                    {
                        Code = "YourAccountIsDisabled",
                        Description = "Your account is disabled"
                    });
                }
                else
                {
                    authenticationResult.IdentityError.Add(new IdentityError
                    {
                        Code = "InvalidLogin",
                        Description = "In valid login!! Please try again"
                    });
                }
            }
            return authenticationResult;
        }
        #region ************Async Envelope**************
        public async Task<ManageDirectoryServices> GetEmployeeByNTIDAsync(string ntid)
        {
            return await Task.Run(() => GetEmployeeByNTID(ntid));
        }
        public async Task<ManageDirectoryServices> GetEmployeeByEmailAsync(string email)
        {
            return await Task.Run(() => GetEmployeeByEmail(email));
        }
        public async Task<ManageDirectoryServices> GetEmployeeByEmpIdAsync(string employeeId)
        {
            return await Task.Run(() => GetEmployeeByEmpId(employeeId));
        }
        public async Task<ManageDirectoryServices> GetManagerAsync()
        {
            return await Task.Run(() => GetManager());
        }
        public async Task<ManageDirectoryServices> GetDirectReportsAsync()
        {
            return await Task.Run(() => GetDirectReports());
        }
        public async Task<AuthenticationResult> SignInAsync(string ntid, string password)
        {
            return await Task.Run(() => SignIn(ntid, password));
        }
        #endregion
        public void Dispose()
        {
            this.Dispose();
            GC.Collect();
        }
    }
}

如何使用

[TestMethod]
        public void ContractorInitialsSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices(MSID);
            var context = manageDirectoryServices.User;
            Assert.AreEqual(MSID, context.SamAccountName);
        }
        [TestMethod]
        public void SignInSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var context = manageDirectoryServices.SignIn(MSID,MSPASSWORD);
            Assert.AreEqual(EMAIL, context.Context.User.EmailAddress);
        }
        [TestMethod]
        public void GetEmployeeByNTIDSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var context = manageDirectoryServices.GetEmployeeByNTID(MSID);
            Assert.AreEqual(MSID, context.User.SamAccountName);
        }
        [TestMethod]
        public void GetManagerSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var context = manageDirectoryServices.GetEmployeeByNTID(MSID);
            var manager = context.GetManager();
            Assert.AreEqual(MANAGER_NTID, context.Manager.SamAccountName);
        }
        [TestMethod]
        public void GetReportesSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var context = manageDirectoryServices.GetEmployeeByNTID(MSID);
            var repcontext = context.GetDirectReports();
            var flag = repcontext.DirectReports.Count > 0 ? true : false;
            Assert.AreEqual(true, flag);
        }
        [TestMethod]
        public void GetEmployeeByEmailSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var context = manageDirectoryServices.GetEmployeeByEmail(EMAIL);
            Assert.AreEqual(EMAIL, context.User.EmailAddress);
        }
        [TestMethod]
        public void GetEmployeeByEmployeeIdSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var context = manageDirectoryServices.GetEmployeeByEmpId(EMPLOYEEID);
            Assert.AreEqual(EMPLOYEEID, context.User.EmployeeId);
        }

        [TestMethod]
        public void IsUserExistSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var IsExist = manageDirectoryServices.IsUserExist(MSID);
            Assert.AreEqual(true, IsExist);
        }
        [TestMethod]
        public void IsUserExistFail()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var IsExist = manageDirectoryServices.IsUserExist("invalidid");
            Assert.AreEqual(false, IsExist);
        }

        [TestMethod]
        public void GetEmployeeSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var searchTemplate = new System.DirectoryServices.AccountManagement.UserPrincipal(manageDirectoryServices.Context) {
                SamAccountName= MSID,
                EmailAddress=EMAIL,
                EmployeeId=EMPLOYEEID
            };
            var context = manageDirectoryServices.GetEmployee(searchTemplate);
            Assert.AreEqual(MSID, context.User.SamAccountName);
        }

        [TestMethod]
        public void GetEmployeeNameSuccess0()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var repcontext = manageDirectoryServices.GetEmployee("abhishek", "givenname");
            var flag = repcontext.DirectReports.Count > 0 ? true : false;
            Assert.AreEqual(true, flag);
        }

        [TestMethod]
        public void GetEmployeeNameSuccess1()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var repcontext = manageDirectoryServices.GetEmployee("abhishek", "name");
            var flag = repcontext.DirectReports.Count > 0 ? true : false;
            Assert.AreEqual(true, flag);
        }

        [TestMethod]
        public void GetEmployeeNameSuccess2()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var repcontext = manageDirectoryServices.GetEmployee("abhishek", "displayname");
            var flag = repcontext.DirectReports.Count > 0 ? true : false;
            Assert.AreEqual(true, flag);
        }