active-directoryasp.net-core-mvcwindows-authenticationprincipalcontext

Accessing user details using Active Directory in an ASP.NET Core MVC app with Windows authentication


I was trying to access user information like first name, last name of the user in my ASP.NET Core MVC project with Windows authentication. I actually make it work after searching for a solution on the web but I am quite new to this stuff and beginner level programmer so not understanding what is happening in the part that I just copy paste in my project.

I couldn't find any explanation in that website as well. I would be really happy if someone can explain this to me. Many thanks in advance.

The website reference for this code: https://sensibledev.com/how-to-get-user-details-from-active-directory/

Home controller:

var username = User.Identity.Name;

using (var context = new PrincipalContext(ContextType.Domain, "yourdomain"))
{
    var user = UserPrincipal.FindByIdentity(context, username);

    if (user != null)
    {
        ViewData["UserName"] = user.Name;
        ViewData["EmailAddress"] = user.EmailAddress;
        ViewData["FullName"] = user.DisplayName;
        ViewData["GivenName"] = user.GivenName;
    }
} 

Solution

  • That code takes the username of the user who logged into your website and looks it up on your domain to find more information about the person.

    var username = User.Identity.Name;
    

    The User property is ControllerBase.User, which refers to the user currently logged into your website. Since you're using Windows Authentication, this will refer to an Active Directory user. User.Identity.Name gets just the username.

    The rest is for looking up the account in Active Directory.

    new PrincipalContext(ContextType.Domain, "yourdomain")
    

    This means "I want to talk to a domain called yourdomain".

    UserPrincipal.FindByIdentity(context, username)
    

    UserPrincipal.FindByIdentity finds an account on the domain. So this is saying "find this username on the domain".

    Then the users details from the account are put into the ViewData collection so that the data is accessible in the view. More details on that here.