?
Solved

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

Posted on 2006-06-01
5
Medium Priority
?
482 Views
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
0
Comment
Question by:freestyle18
  • 4
5 Comments
 
LVL 6

Accepted Solution

by:
SandeepRR earned 1500 total points
ID: 16814553
                 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);
                  userListTable.Columns.Add(userSAMName);
                  //Data column to contain users Name.
                  DataColumn userNameColumn = new DataColumn("UserNameColumn");
                  userNameColumn.DataType = typeof(System.String);
                  userListTable.Columns.Add(userNameColumn);
                  //Data column to contain users mailID.
                  DataColumn userMailIDColumn = new DataColumn("UserMailIDColumn");
                  userMailIDColumn.DataType = typeof(System.String);
                  userListTable.Columns.Add(userMailIDColumn);
                  
                  try
                  {
                        //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.
                        directorySearcher.PropertiesToLoad.Add(SAMNAME);
                        //Load the property of distinguishedName as will contains distinguishName of user in AD.
                        directorySearcher.PropertiesToLoad.Add(DNNAME);
                        directorySearcher.PropertiesToLoad.Add(USERNAME);
                        directorySearcher.PropertiesToLoad.Add(MAILID);

                        try
                        {
                              //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="
                                          else
                                          {
                                                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];
                                    }
                                    else
                                    {
                                          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];
                                    }
                                    else
                                    {
                                          userMailID = "";
                                    }
                                    //Add user mail id in the column of the row.
                                    oneUserRow["UserMailIDColumn"] = userMailID;

                                    userListTable.Rows.Add(oneUserRow);
                              }

                        }
                  }
                  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
.PropertiesToLoad.Add("givenname")
.PropertiesToLoad.Add("cn")
.PropertiesToLoad.Add("nGWVisibility")
.PropertiesToLoad.Add("nGWObjectID")
.PropertiesToLoad.Add("nGWPostOffice")
.PropertiesToLoad.Add("nGWFileID")
.PropertiesToLoad.Add("Fullname")
.PropertiesToLoad.Add("sn")
.PropertiesToLoad.Add("logintime")
.PropertiesToLoad.Add("loginDisabled")
.PropertiesToLoad.Add("ndsHomeDirectory")
.PropertiesToLoad.Add("groupMembership")

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

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


SandeepRR
0
 

Author Comment

by:freestyle18
ID: 16817188
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.

MikeD
0
 

Author Comment

by:freestyle18
ID: 16818857
This is what I've come up with so far...in VB.net 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
        oSearcher.PropertiesToLoad.Add("cn")
        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
0
 

Author Comment

by:freestyle18
ID: 16819092
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://tpssad1.tangi.org/DC=Tangi,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 = ""
        Try

            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

        Catch
            Throw
        Finally
            If Not IsNothing(entry) Then
                entry.Dispose()
            End If
            If Not IsNothing(searcher) Then
                searcher.Dispose()
            End If
        End Try
0
 

Author Comment

by:freestyle18
ID: 16823195
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.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
Suggested Courses
Course of the Month15 days, 10 hours left to enroll

850 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