CodeDigest.Com Logo
Featured:

Get User Details from Active Directory in Asp.Net MVC

Tagged as: Asp.Net Asp.Net MVC Posted By

In my previous article Forms Authentication Using Active Directory Users in Asp.Net MVC, we have built an Asp.Net MVC application which authenticates users from Active Directory using Forms Authentication. In a continuation of that, let’s build a profile page to display the user details fetched from Active directory. We will use Galactic API package in this article too for Active Directory interaction. Galactic API is a free, open source package that can be used in .Net application to interact with Active Directory.

Note – I will be using same project where we have built Forms Authentication to authenticate users in Active Directory. Read Forms Authentication Using Active Directory Users in Asp.Net MVC to know more.  Skip to Fetching User Details From Active Directory section if you are reading this article in continuation of previous article.

Let’s create an Asp.Net MVC application in Visual Studio 2015(2013 or 2015) and select “Individual User Accounts” or “Internet Application”.

First, let’s add Galactic API package in our project using Nuget Package Manager. To do this, right click your project in Solution explorer and Click Manage Nuget Packages...Search for “Galactic.ActiveDirectory” and click Install. This will install all the required components and dependent packages into our project.

Fetching User Details from Active Directory

In AccountController, add action method called userprofile() to fetch the user details from active Directory. Code below,

       

public ActionResult UserProfile()

        {

            string serverName = ConfigurationManager.AppSettings["ADServer"];

            string userName = ConfigurationManager.AppSettings["ADUserName"];

            string password = ConfigurationManager.AppSettings["ADPassword"];

            SecureString securePwd = null;

            if (password != null)

            {

                securePwd = new SecureString();

                foreach (char chr in password.ToCharArray())

                {

                    securePwd.AppendChar(chr);

                }

            }

            UserProfile usrProfile = new UserProfile();

            try

            {

                ActiveDirectory adConnect = new ActiveDirectory(serverName, userName, securePwd);

                List<SearchResultEntry> results = adConnect.GetEntriesBySAMAccountName(User.Identity.Name);

                if (results.Count > 0)

                {

                    User usr = new User(adConnect, results[0]);

                    usrProfile.FirstName = usr.FirstName;

                    usrProfile.LastName = usr.LastName;

                    usrProfile.Manager = usr.Manager;

                    usrProfile.Department = usr.Department;

                    usrProfile.Division = usr.Division;

                    usrProfile.EmployeeId = usr.EmployeeId;

                    usrProfile.EmployeeNumber = usr.EmployeeNumber;

                    usrProfile.PhoneNumber = usr.PhoneNumber;

                    usrProfile.StreetAddress = usr.StreetAddress;

                    usrProfile.Title = usr.Title;

                    usrProfile.UserName = usr.DisplayName;

                    usrProfile.Groups = usr.Groups;

                }

            }

            catch

            {

                // unable to connect AD

                ModelState.AddModelError("", "Unable to connect AD!");

            }

            return View(usrProfile);

        }

 

 

Add the following AppSettings in your Web.Config file.

   

    <add key="ADServer" value="[AD Server Name]" />

    <add key="ADUserName" value="[username]" />

    <add key="ADPassword" value="[password]" />

 

 

The username specified above should have access to the Active Directory server.

User Profile View Model:

 

public class UserProfile

    {     

        public string UserName { get; set; }

        public string Title { get; set; }

        public string Department { get; set; }

        public string DisplayName { get; set; }

        public string Division { get; set; }

        public string EmployeeId { get; set; }

        public string EmployeeNumber { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string Manager { get; set; }

        public string PhoneNumber { get; set; }

        public string StreetAddress { get; set; }

        public List<string> Groups { get; set; }

    }

 

 

The above code connects the Active Directory server using username and password specified in Web.Config and will fetch the logged in user details for you. To fetch a different user details pass the appropriate username while calling the method GetEntriesBySAMAccountName() bolded above.

 

 

Download the source and configure the AppSettings value appropriately. After logging in, click your user name link on top right corner to see the profile page.

Checking User Part of an Active Directory Group

There is a property called Groups exposed by Galactic API User object (inherited from SecurityPrincipal class) which gives us list of groups to check this.  But, most of the times we will need check if the logged-in user is part of an AD group(or role) before doing some operations. The below method can be used for that.

 

        public bool CheckUserInGroup(string group)

        {

            string serverName = ConfigurationManager.AppSettings["ADServer"];

            string userName = ConfigurationManager.AppSettings["ADUserName"];

            string password = ConfigurationManager.AppSettings["ADPassword"];

            bool result = false;

            SecureString securePwd = null;

            if (password != null)

            {

                securePwd = new SecureString();

                foreach (char chr in password.ToCharArray())

                {

                    securePwd.AppendChar(chr);

                }

            }

            try

            {  

                ActiveDirectory adConnectGroup = new ActiveDirectory(serverName, userName, securePwd);

                SearchResultEntry groupResult = adConnectGroup.GetEntryByCommonName(group);

                Group grp = new Group(adConnectGroup, groupResult);

                SecurityPrincipal userPrincipal = grp.Members.Find(sp => sp.SAMAccountName.ToLower() == User.Identity.Name.ToLower());

                if (userPrincipal != null)

                {

                    result = true;

                }

            }

            catch

            {

                result = false;

            }

            return result;

        }

 

 



Feedback

Comments

thank you
It's working Thank you so much !!!!!!!
Commented by Orn on 7/16/2018 1:36:38 AM

Login incorrect
No errors in code but all logins fail with incorrect login?
Commented by Mortenjj on 5/31/2018 7:04:55 AM