13

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?

twal
  • 6,999
  • 17
  • 48
  • 58

4 Answers4

23

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
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • @twal don't forget to accept this answer if it worked for you. – Waleed Al-Balooshi Feb 10 '11 at 18:36
  • @marc_s what I am curious about is how I should go about storing this user information to prevent too many taps on AD. Cookie or Session[] collection? Or something else? All I want to do is save duder's display name for later without having to tap AD each time a request comes to IIS. What do you think? – one.beat.consumer Jan 24 '12 at 02:40
5

If your code is running under the context of the user that you need information for, it gets even lighter (i.e. Windows Authentication):

//Must reference System.DirectoryServices.AccountManagement
var user = UserPrincipal.Current;

var firstName = user.GivenName;
var lastName = user.Surname;
Kevin Kalitowski
  • 6,829
  • 4
  • 36
  • 52
  • If I wanted to use this in the MVC layout page, would this code go in the Model, View, or Controller? Sorry, I've only begun MVC a week ago and am still trying to figure it all out. – Jamie Nov 06 '18 at 18:18
1

Sounds like you may want to use the System.DirectoryServices namespace. Here's a guide on how you can read properties of a Directory object.

bhamby
  • 15,112
  • 1
  • 45
  • 66
0

In my environment I had to add this to the section in Web.config:

<identity impersonate="true" />
Pete
  • 1,191
  • 12
  • 19