.Netcore AD 操作
阿新 • • 發佈:2020-08-27
1. NUget引入:
System.DirectoryServices
System.DirectoryServices.AccountManagement
2 登陸種情況:有登陸介面和無登陸介面
2.1. 有登陸介面,有表單,輸入使用者名稱密碼,後臺拿到使用者名稱密碼,找AD 伺服器驗證
protected virtual bool ValidateCredentials(PrincipalContext principalContext, string userNameOrEmailAddress, string plainPassword) { return principalContext.ValidateCredentials(userNameOrEmailAddress, plainPassword, ContextOptions.Negotiate); }
2.2. 無登陸介面,瀏覽器彈出密碼輸入框。
需要做的有:
- IIS 支援安裝 Windows Authentication
- .NetCore 選擇windows 認證。
- Action上帶上 Authoriz(…) (.NetCore 3.1 模板,自己會加上這一步。)
3.根據組名獲取郵箱(下面程式碼是先獲取組成員,再得到他的郵箱):
public string[] GetEmails(string groupName) { DirectorySearcher ds = new DirectorySearcher(); ds.SearchRoot= new DirectoryEntry("LDAP://" + _appConfiguration["Container"]); ds.Filter = $"(&(objectClass=group)(cn={groupName}))"; var ms = new List<string>(); foreach (SearchResult result in ds.FindAll()) { DirectoryEntry deGroup = new DirectoryEntry(result.Path);var pcoll = deGroup.Properties["member"]; for (int l = 0; l < pcoll.Count; l++) { var n = pcoll[l].ToString(); DirectoryEntry deUser = new DirectoryEntry($"LDAP://{n}"); ms.Add(deUser.Properties["mail"][0].ToString()); } } return ms.ToArray(); }