Question about validating an ASP.NET 2.0 site to Active Directory

Posted on 2006-06-01
Last Modified: 2008-01-09
I have created a test site in ASP.NET 2.0 and actually gotten the Active Directory authentication to work correctly.  So when I put in my Active Directory username and password into my login control, it authenticates fine and brings me to the LoggedIn Template.  That's great, I'm glad that was fairly straight-forward.  My question is can I gather any other info about the logged in user from AD?  I would love to be able to use the DisplayName property from AD that goes with the logged in username.  Is this possible?  And if it is possible, could someone give me some direction as to how to do it?

Mike Diaz
Question by:freestyle18
    LVL 6

    Accepted Solution

                     SearchResultCollection resultCollection = null;
                      //Data table to contain all users
                      DataTable userListTable = new DataTable("UsersList");                  
                      //Data column to contain users ID with domain.
                      DataColumn userSAMName = new DataColumn("UserSAMName");
                      userSAMName.DataType = typeof(System.String);
                      //Data column to contain users Name.
                      DataColumn userNameColumn = new DataColumn("UserNameColumn");
                      userNameColumn.DataType = typeof(System.String);
                      //Data column to contain users mailID.
                      DataColumn userMailIDColumn = new DataColumn("UserMailIDColumn");
                      userMailIDColumn.DataType = typeof(System.String);
                            //Create a directory searcher object and pass a LDAP query to it.
                            DirectorySearcher directorySearcher =
                                  new DirectorySearcher(new DirectoryEntry("LDAP://User Domain NAme"));
                            //Filter the searcher object for objects having type as users.
                            //directorySearcher.Filter = "(&(objectClass=user)(objectCategory=person))";
                            directorySearcher.Filter = String.Format("(cn={0})","Sandeep R");
                            //Set page size to 2000 so that all user can be found in the batch of 2000.
                            directorySearcher.PageSize = 2000;
                            //Load the property of samaccountname as it contains userid in AD.
                            //Load the property of distinguishedName as will contains distinguishName of user in AD.

                                  //Find all the users for the query string
                                  resultCollection = directorySearcher.FindAll();
                            catch(Exception ex)
                            if (resultCollection != null)
                                  //Run the loop for every search result found.
                                  for(int counter=0; counter < 100; counter++)
                                        string userIDWithDomain = "";
                                        string domainName = "";
                                        string userName = "";
                                        string userMailID = "";

                                        //Creates a datarow that will contain the userIDwithDomain of the user.
                                        DataRow oneUserRow = userListTable.NewRow();
                                        SearchResult result = resultCollection[counter];
                                        //Check the samaccountname propery from AD.
                                        if (result.Properties.Contains(SAMNAME))
                                              userIDWithDomain = (string) result.Properties[SAMNAME][0];
                                        //Check the distinguishedName property.
                                        if (result.Properties.Contains(DNNAME))
                                              //Get distinguishedName. Sample string is "CN=Sato T,CN=Users,DC=Toshiba,DC=com"
                                              string dnNameString = (string) result.Properties[DNNAME][0];
                                              //Get the index of first "DC=" as it will contain the domain name of the user.
                                              Int32 dcIndex = dnNameString.ToUpper().IndexOf(DC_CONST.ToString());
                                              //Get the index of ',' after index of "DC="
                                              Int32 commaIndex = dnNameString.IndexOf(",", dcIndex + 1);

                                              //this is the condition when there is ',' in the string after "DC="
                                              if(commaIndex != -1)
                                                    //Get the domain name by string manipulation.
                                                    //If sample string is "CN=Sato T,CN=Users,DC=Toshiba,DC=com",
                                                    //then get the word "Toshiba" out of it.
                                                    domainName = dnNameString.Substring(dcIndex + DC_CONST.Length,
                                                          dnNameString.IndexOf(",", dcIndex + 1) - dcIndex - DC_CONST.Length);
                                                    //If there is no ',' after "DC=" then get the whole string after "DC="
                                                    domainName = dnNameString.Substring(dcIndex + 3);
                                        //Create the UserIDWithDomain
                                        userIDWithDomain = domainName+ "\\" + userIDWithDomain;
                                        oneUserRow["UserSAMName"] = userIDWithDomain;

                                        //Check the "name" property as it contins display name of the user
                                        if (result.Properties.Contains(USERNAME))
                                              userName = (string) result.Properties[USERNAME][0];
                                              userName = userIDWithDomain;
                                        //Add user name in the column of the row.
                                        oneUserRow["UserNameColumn"] = userName;

                                        //Check for the "mail" property as it contains the e-mail of the user.
                                        if (result.Properties.Contains(MAILID))
                                              userMailID = (string) result.Properties[MAILID][0];
                                              userMailID = "";
                                        //Add user mail id in the column of the row.
                                        oneUserRow["UserMailIDColumn"] = userMailID;


                      catch(Exception ex)

    this is the code which will give u the login name, Name of that person and the email ID

    or u can also use following properties to get the different info

    also in above code i am using the table to add the search result
    also in one pleace u have to add user Domain name "User Domain Name"--in thib place

    replace the search filter and change the name ,this is the Name not the login Name,,


    Author Comment

    Obviously I'm not nearly as informed as I should be with this, because you lost me right away =/  The DirectorySearcher class I am definitely not up on, I'm not even sure how to declare it.  It looks like you put alot of thought into your answer, but obviously I need it broken down even further.


    Author Comment

    This is what I've come up with so obviously.  Of course, it doesn't work.  I think part of my problem is the "loginname1.ID".  I'm trying to pull that parameter becuase I know it has the username stored, but I'm not sure how to do it to include it in my search string.  Any advice or comments on this?

    Imports System.DirectoryServices

    Partial Class _Default
        Inherits System.Web.UI.Page

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Dim de As DirectoryEntry = New DirectoryEntry("LDAP://<Servername>/DC=Domain,DC=org")
            Dim FullName As String = ""
            Dim oSearcher As DirectorySearcher = New DirectorySearcher(de)
            oSearcher.Filter = "(&(objectCategory=person)(sAMAccountName=" + LoginName1.ID + "))"
            Dim oResult As SearchResult
            oResult = oSearcher.FindOne
            If (Not (oResult) Is Nothing) Then
                If oResult.Properties.Contains("displayName") Then
                    FullName = oResult.Properties("displayName")(0).ToString.ToUpper
                End If
            End If
            Label1.Text = FullName

        End Sub
    End Class

    Author Comment

    Ok, I scrapped the above and received this code from this site and modified it to what I needed.  This definitely works IF I replace "LoginName1" with an actual username.  LoginName1 is the ID of the authenticated user that logged into the website.  What am I doing wrong?

    Dim ldapPath As String = "LDAP://,DC=org"
            Dim filter As String = String.Format("(&(objectClass=user)(objectCategory=person)(sAMAccountName={0}))", LoginName1)

            Dim entry As New DirectoryEntry(ldapPath)
            Dim searcher As New DirectorySearcher(entry, filter, New String() {"givenName", "sn"})
            Dim fullName As String = ""

                Dim result As SearchResult = searcher.FindOne()
                If Not IsNothing(result) Then
                    If Not IsNothing(result.Properties("givenName")) Then
                        lblFirst.Text = result.Properties("givenName")(0)
                    End If
                    If Not IsNothing(result.Properties("sn")) Then
                        lblLast.Text = " " + result.Properties("sn")(0)
                    End If
                End If

                If Not IsNothing(entry) Then
                End If
                If Not IsNothing(searcher) Then
                End If
            End Try

    Author Comment

    Ok, well I guess just typing in here allowed me to solve my own problem.  I just replaced "loginname1" with "User.Identity.Name" and it works perfectly.  I'll give the points for the time you put in...thanks alot.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    What Should I Do With This Threat Intelligence?

    Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

    Lots of people ask this question on how to extend the “MembershipProvider” to make use of custom authentication like using existing database or make use of some other way of authentication. Many blogs show you how to extend the membership provider c…
    A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
    Internet Business Fax to Email Made Easy - With eFax Corporate (, you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
    Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

    779 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now