• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 848
  • Last Modified:

how to read users information from active directory in asp.net application

i am writing a application in asp.net 2.0  to read the users from active directory.
but i am receiving error as : a referral was returned from the server in .net application

my code  is:
Try
          Dim path As String = "LDAP://100.0.0.1/CN=Users,DC=firm,DC=domainname,DC=com"
            Dim AD As DirectoryEntry = New DirectoryEntry(path)
            AD.Username = "domainname\username"
            AD.Password = "password"

            AD.Children.SchemaFilter.Add("users")
            Dim obj As DirectoryEntry
            For Each obj In AD.Children

                'Dim replaced As String = FixString(obj.Name.ToString(), "CN=", "")
                Dim replaced As String = obj.Name.ToString()
                'replaced = FixString(replaced, "\\", "")
                ADUsersList.Items.Add(replaced)

            Next
        Catch e As Exception

            'MsgBox("Error is " & e.Message)
            'Return RetArray

        End Try
0
softtt
Asked:
softtt
  • 9
  • 7
  • 2
1 Solution
 
Muhammad Ousama GhazaliSolution Analyst & ArchitectCommented:
0
 
Chris DentPowerShell DeveloperCommented:

It isn't the cause of your problem, but this won't help much:

> AD.Children.SchemaFilter.Add("users")

The filter should be "user" not "users". "user" is the objectClass you're filtering to.

Otherwise I agree with moghazali. The most likely cause of your problem is an invalid value for "path".

Chris
0
 
softttAuthor Commented:

Dea rmoghazali:

from the second link i found that it says add the domain control name
in the code i already added the domainname
Dim path As String = "LDAP://100.0.0.1/CN=Users,DC=firm,DC=domainname,DC=com"

even though same error.


0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
Muhammad Ousama GhazaliSolution Analyst & ArchitectCommented:
Please try replacing IP address with the "domainname" and check. If the full domain name is something like "mydomain.org" then replace IP with "mydomain.org" rather than "mydomain". In you sample, I think it would be a ".com".
0
 
softttAuthor Commented:

Dear moghazali:

i replace the IP with the domain name , even though same error.
0
 
Muhammad Ousama GhazaliSolution Analyst & ArchitectCommented:
Try using the code below, I am pasting a modified version from a running implementation. Hope this helps.
Private Function GetDomainUsers(ByVal domainName As String, Optional ByVal userName As String = "", Optional ByVal password As String = "") As DataTable
 
	Dim dtDomainUsers As DataTable = Nothing
	Dim count As Integer
	Dim dirEntry As DirectoryEntry = Nothing
	Dim dirSearcher As DirectorySearcher = Nothing
	Dim resultCollection As SearchResultCollection = Nothing
	Dim blnPassCredentials As Boolean = False
 
	Try
		dirEntry = New DirectoryEntry(GetLdapFormattedDomainName(domainName))
 
		If userName.Length > 0 Then dirEntry.Username = userName : blnPassCredentials = True
 
		If password.Length > 0 Then dirEntry.Password = password : blnPassCredentials = True
 
		If blnPassCredentials Then dirEntry.AuthenticationType = AuthenticationTypes.Secure
 
		dirSearcher = New DirectorySearcher(dirEntry)
 
		With dirSearcher
 
			.Sort = New SortOption("samAccountName", SortDirection.Ascending)
 
			.Filter = "(objectCategory=User)"	' search filter
 
			.PropertyNamesOnly = True
 
			.PropertiesToLoad.Add("samAccountName")
			.PropertiesToLoad.Add("displayName")
 
			.SearchScope = SearchScope.Subtree
 
			.PageSize = 500
 
		End With
 
		resultCollection = dirSearcher.FindAll()
 
		count = resultCollection.Count
 
		If count > 0 Then
 
  		dtDomainUsers = New DataTable("DomainUsers")
			dtDomainUsers.Columns.Add("LogonName")
			dtDomainUsers.Columns.Add("FullName")
			dtDomainUsers.Columns.Add("Sid")
 
			Dim rowTemp As DataRow = Nothing
 
			For intIterate As Integer = 0 To count - 1 Step 1
 
				rowTemp = dtDomainUsers.NewRow()
				rowTemp("LogonName") = resultCollection(intIterate).GetDirectoryEntry().Properties("samAccountName").Value
				rowTemp("FullName") = resultCollection(intIterate).GetDirectoryEntry().Properties("displayName").Value
				rowTemp("Sid") = resultCollection(intIterate).GetDirectoryEntry().Properties("objectSid").Value
 
				dtDomainUsers.Rows.Add(rowTemp)
 
			Next intIterate
 
		End If
 
	Catch ex As Exception
    Throw
 
	End Try
 
	Return dtDomainUsers
 
End Function
 
Private Function GetLdapFormattedDomainName(ByVal domainName As String) As String
	'Generic Return Sample: "LDAP://<domainName>/DC=<domainNamePart1>,DC=<domainNamePart2>,DC=<domainNamePartN>"
	'Specific Return Sample: "LDAP://mydomain/DC=mydomain,DC=com,DC=pk" where domainName = mydomain.com.pk
 
	If domainName Is Nothing OrElse domainName.Length = 0 Then Throw New ArgumentNullException("domainName")
 
	Dim strDomainName As String()
	Dim strQuery As String = String.Empty
 
	If domainName.IndexOf(".") >= 0 Then
 
		strDomainName = domainName.Split(".")
 
		For Each item As String In strDomainName
 
			strQuery &= "DC=" & item & ","
 
		Next
 
		strQuery = strQuery.Substring(0, strQuery.Length - 1)
 
	End If
 
	domainName = "LDAP://" & domainName
 
	If strQuery.Length > 0 Then domainName &= "/" & strQuery
 
	Return domainName
 
End Function

Open in new window

0
 
Chris DentPowerShell DeveloperCommented:

The return of a Referral does indicate that you're talking to an LDAP server, so the IP / domain name portion is fine. I would verify the LDAP path you're passing it: "CN=Users,DC=firm,DC=domainname,DC=com". It looks fine at first glance assuming the domain is "firm.domainname.com".

Chris
0
 
softttAuthor Commented:
dear moghazali:

very very very Thanks a lot for your help
with your code i got the information.
actually i tested this in my virtual machines, i created 2 virtual machine 1 is server and 1 is domain,
then i retrieve the information from domain ,
let me test this in real environment

regards.
shams




0
 
softttAuthor Commented:

Dear moghazali:

now i am creating a login page.  and check that user from this active directory,
how i can give authenticate from this active directory.
if user is available in this active directory. then he will be login to proceed.

i need help from you.

regards
shams
0
 
Muhammad Ousama GhazaliSolution Analyst & ArchitectCommented:
Now, instead of a code used by me, I am refering you to an official documentation page which have a good example and explanation how you could do that:
http://support.microsoft.com/kb/326340 and/or http://msdn.microsoft.com/en-us/library/ms998360.aspx
 Hope this helps.
0
 
softttAuthor Commented:

Dear moghazali:

very very thanks for your solution , i got success from the above links,

regards.
shams
0
 
softttAuthor Commented:
Dear moghazali:

very very thanks for your solution , i got success from the above links,

regards.
shams
0
 
Muhammad Ousama GhazaliSolution Analyst & ArchitectCommented:
I am glad that it helped. Happy programming.
0
 
softttAuthor Commented:
Dear moghazali:

when i publish this active directory application i am getting error.

Error authenticating. Error authenticating user. Logon failure: unknown user name or bad password
but it works fine in my local p.c.

regards
shams.
0
 
Muhammad Ousama GhazaliSolution Analyst & ArchitectCommented:
Hi,
Use the function GetDomainUsers with user name and password being passed. This user name/password must be of an active account within the Domain whose name is passed as first argument and where probably you are publishing your side.
One other alternative might be to use personalization in ASP.NET. Check if the above works otherwise I'll try to point you to some resources on ASP.NET personalization.
0
 
Muhammad Ousama GhazaliSolution Analyst & ArchitectCommented:
Correction: ASP.NET Impersonation
0
 
softttAuthor Commented:

Dear moghazali:

when i publish in my local p.c also it is not working.
if i run the application it works fine.

regards
shams
0
 
softttAuthor Commented:
Dears,

please any body help.
i am using this class to retrieve users information from active directory.
first time when i am login its work fine, but even i am searching again the variable of (filterAttributeDept ) value is empty.

Public Function IsAuthenticated(ByVal domain As String, ByVal username As String, ByVal pwd As String) As Boolean

        Dim domainAndUsername As String = domain & "\" & username
        Dim entry As DirectoryEntry = New DirectoryEntry(_path, domainAndUsername, pwd)

        Try
            'Bind to the native AdsObject to force authentication.                  
            Dim obj As Object = entry.NativeObject
            Dim search As DirectorySearcher = New DirectorySearcher(entry)

            search.Filter = "(SAMAccountName=" & username & ")"
            search.PropertiesToLoad.Add("cn")
            search.PropertiesToLoad.Add("department")
            search.PropertiesToLoad.Add("memberOf")
            search.PropertiesToLoad.Add("Pager")
            search.PropertiesToLoad.Add("Aliases")
            Dim result As SearchResult = search.FindOne()

            If (result Is Nothing) Then
                Return False
            End If

            'Update the new path to the user in the directory.
            _path = result.Path
            _filterAttribute = CType(result.Properties("cn")(0), String)
            _filterAttributeDept = CType(result.Properties("memberOf")(2), String)

            'Session("FilterAtt") = _filterAttributeDept

        Catch ex As Exception
            Throw New Exception("Error authenticating user. " & ex.Message)
        End Try

        Return True
    End Function
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 9
  • 7
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now