Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Active Directory Info when using Windows Authentication?

I am using Windows authentication on my asp.net MVC 3 app. Is there any way possible to get the users information out of active directory?

I know I can user User.Name.Identity and that works for the login name. But what about getting the Users First Name, Last Name and even the Description or Office all from active directory. Is this possible through .net?

like image 421
twal Avatar asked Feb 10 '11 18:02

twal


1 Answers

Of course!! If you're using .NET 3.5 or up, it's actually pretty easy.

Basically, use the System.DirectoryServices.AccoutManagement namespace (read all about it here: Managing Directory Security Principals in the .NET Framework 3.5).

Then: you need to "find" the user and grab it's properties - use code something like this:

// create domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find the user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "username");

if(user != null)
{
    // access the user's properties in a nice, object-oriented way
}
like image 154
marc_s Avatar answered Oct 21 '22 23:10

marc_s