Retrieve user information from Active Directory on login

1.1k views Asked by At

I build one page ASP.Net required to login with Active Directory. The login is successful. But how to retrieve current user information from AD such as Full Name and display in my mainpage.aspx (C#)

I have try this on my code

using System.DirectoryServices;

   using (DirectoryEntry de = new DirectoryEntry("LDAP://SUTRA"))
        {
            using (DirectorySearcher adSearch = new DirectorySearcher(de))
            {
                string username = HttpContext.Current.Request.ServerVariables["AUTH_USER"];
                adSearch.Filter = "(sAMAccountName=someuser)";
                SearchResult adSearchResult = adSearch.FindOne();
            }
        }
1

There are 1 answers

0
jaycyborg On

The following code will return User's FirstName and LastName from AD

  public string GetUserDetails(string UserID)
    {
        try
        {
            DirectorySearcher search = default(DirectorySearcher);
            DirectoryEntry entry = default(DirectoryEntry);
            SearchResult sr = default(SearchResult);
            System.DirectoryServices.PropertyCollection propertycol = default(System.DirectoryServices.PropertyCollection);
            entry = new DirectoryEntry("LDAP://DomainName.com");
            propertycol = entry.Properties;
            search = new DirectorySearcher(entry);
            search.Filter = "(sAMAccountName=" + UserID + ")";                
            sr = search.FindOne();
            string fname = "";
            string lname = "";

            if ((sr != null))
            {
                if (sr.Properties.Count > 1)
                {
                    fname = Convert.ToString(sr.GetDirectoryEntry().Properties["givenName"].Value);

                    lname = Convert.ToString(sr.GetDirectoryEntry().Properties["sn"].Value);
                }
                return fname + "\n" + lname ;
            }

          return "User Id not found";
        }
        catch (Exception ex)
        {
            return "Error:" + ex.Message;
        }
    }