Get UserPrincipal by employeeID

懵懂的女人 提交于 2020-01-02 05:00:06

问题


I have implemented System.DirectoryServices.AccountManagement for authentication into my webapps finding users (UserPrincipal) byidentity given username. However, I have several cases where I need to get AD accounts given only an employeeID. Is there a good way to get a UserPrincipal (or even just the sAMAccountName) given an employeeID in AccountManagement?

I currently have this working to grab users by username:

PrincipalContext adAuth = new PrincipalContext(ContextType.Domain, Environment.UserDomainName);

//get user
UserPrincipal usr = UserPrincipal.FindByIdentity(adAuth, username);

I have been searching and can't seem to find answers to confirm whether this can or cannot be done. If I can't do it with AccountManagement, what's the best way to get sAMAccountName given employeeID?


回答1:


You don't need to go outside of the System.DirectoryServices.AccountManagement namespace.

UserPrincipal searchTemplate = new UserPrincipal(adAuth);
searchTemplate.EmployeeID = "employeeID";
PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);

UserPrincipal user = (UserPrincipal)ps.FindOne();

In this example, if no user is found the user object will be null. If you want to find a collection of UserPrinicipal object you can use the FindAll method on the PrincipalSearcher (ps) object.

Also note that the FindOne method returns a Principal object, but we know it is really a UserPrincipal and should be handled (casted) as such since UserPrincipal is part of the search filter.




回答2:


So, I found a way using System.DirectoryServices as below, but it seems rather lengthy:

string username = "";

DirectoryEntry entry = new DirectoryEntry(_path);

//search for a DirectoryEntry based on employeeID
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(employeeID=" + empID + ")";

//username
search.PropertiesToLoad.Add("sAMAccountName");

SearchResult result = search.FindOne();

//get sAMAccountName property
username = result.Properties["sAMAccountName"][0].ToString();

Of course, I could use this for the other attributes, but I really like the strongly-typed attributes with AccountManagement.



来源:https://stackoverflow.com/questions/23916328/get-userprincipal-by-employeeid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!