Solved

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

Posted on 2009-05-17
18
824 Views
Last Modified: 2012-05-07
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
Comment
Question by:softtt
  • 9
  • 7
  • 2
18 Comments
 
LVL 11

Expert Comment

by:Muhammad Ousama Ghazali
ID: 24409477
0
 
LVL 71

Expert Comment

by:Chris Dent
ID: 24409894

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
 

Author Comment

by:softtt
ID: 24419008

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
Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

 
LVL 11

Expert Comment

by:Muhammad Ousama Ghazali
ID: 24419110
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
 

Author Comment

by:softtt
ID: 24419192

Dear moghazali:

i replace the IP with the domain name , even though same error.
0
 
LVL 11

Expert Comment

by:Muhammad Ousama Ghazali
ID: 24419240
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
 
LVL 71

Expert Comment

by:Chris Dent
ID: 24419469

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
 

Author Comment

by:softtt
ID: 24419636
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
 

Author Comment

by:softtt
ID: 24419719

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
 
LVL 11

Accepted Solution

by:
Muhammad Ousama Ghazali earned 500 total points
ID: 24419879
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
 

Author Comment

by:softtt
ID: 24455031

Dear moghazali:

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

regards.
shams
0
 

Author Closing Comment

by:softtt
ID: 31582488
Dear moghazali:

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

regards.
shams
0
 
LVL 11

Expert Comment

by:Muhammad Ousama Ghazali
ID: 24455661
I am glad that it helped. Happy programming.
0
 

Author Comment

by:softtt
ID: 24467798
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
 
LVL 11

Expert Comment

by:Muhammad Ousama Ghazali
ID: 24467993
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
 
LVL 11

Expert Comment

by:Muhammad Ousama Ghazali
ID: 24468125
Correction: ASP.NET Impersonation
0
 

Author Comment

by:softtt
ID: 24468394

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
 

Author Comment

by:softtt
ID: 24550075
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

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

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

Suggested Solutions

In-place Upgrading Dirsync to Azure AD Connect
Active Directory security has been a hot topic of late, and for good reason. With 90% of the world’s organization using this system to manage access to all parts of their IT infrastructure, knowing how to protect against threats and keep vulnerabil…
This video teaches viewers how to create their own website using cPanel and Wordpress. Tutorial walks users through how to set up their own domain name from tools like Domain Registrar, Hosting Account, and Wordpress. More specifically, the order in…
Learn how to set-up PayPal payment integration in your Wufoo form. Allow your users to remit payment through PayPal upon completion of your online form. This is helpful for collecting membership payments, customer payments, donations, and more.

679 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