Get UserPrincipal by employeeID
Asked Answered
R

2

6

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?

Roark answered 28/5, 2014 at 15:49 Comment(0)
D
13

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.

Dishpan answered 18/12, 2015 at 0:33 Comment(1)
I know this was an old post, but I'll give this a try and mark answer if it works well. Thanks!Roark
R
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.

Roark answered 28/5, 2014 at 17:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.