Growth sometimes brings out the unexpected flaws in designs. What seems like a quick solution, may intern lead to what I have affectionately call 'Learning Opportunities'.After a recent expansion from a single domain environment to a multi-domain forest, the following VB.Net function ceased functioning for retrieving the user's full name.
Public Shared Function GetADUserName() As String
Dim returnString As String = String.Empty
If HttpContext.Current.User.Identity.IsAuthenticated Then
Try
Dim DomainUser As String = WindowsIdentity.GetCurrent.Name.Replace("\", "/")
Dim ADEntry As New DirectoryEntry("WinNT://" & DomainUser)
Dim FullName As String = ADEntry.Properties("FullName").Value
returnString = FullName.Substring(FullName.LastIndexOf(",") + 1)
returnString &= " " & FullName.Substring(0, FullName.LastIndexOf(","))
Catch ex As Exception
Finally
End Try
End If
Return returnString
End Function
Doing some research resulted in the realization that the WinNT provider would only work correctly in a 'flat domain'. Some modifications to an existing application allowed for the following replacement utilizing the LDAP provider in the DirectoryServices library. The key is to enable Referral Chasing.
Public Shared Function GetADUserName() As String
Dim returnString As String = String.Empty
If HttpContext.Current.User.Identity.IsAuthenticated Then
Try
' Set the root search path
Dim ldapPath As String = "LDAP://DC=MyDomain,DC=COM"
Dim entry As New DirectoryEntry(ldapPath)
' AppSettings holds username and password
' This allows the query to run outside the context of the impersonated user
' This user currently is delegated rights in AD
entry.Username = ConfigurationManager.AppSettings("AdUser").ToString
entry.Password = ConfigurationManager.AppSettings("ADPassword").ToString
entry.AuthenticationType = AuthenticationTypes.Secure
' Retrieve the current user's ntid
Dim DomainUser As String = WindowsIdentity.GetCurrent.Name.Substring
(WindowsIdentity.GetCurrent.Name.LastIndexOf("\"))
' Set your filter
Dim filter As String =
String.Format("(&(objectClass=user)(sAMAccountName={0}))", DomainUser)
Dim searcher As New DirectorySearcher(entry, filter, New String() {"displayName"})
' Allow searches to span multiple domain referrals
searcher.ReferralChasing = ReferralChasingOption.All
Dim result As SearchResult = searcher.FindOne()
If Not IsNothing(result) Then
'Verify the property was returned
If (result.Properties.Contains("displayName")) Then
returnString = result.Properties("displayName")(0)
End If
End If
Catch ex As Exception
'Some error handling here
Finally
End Try
End If
Return returnString
End Function
Posted
Oct 01 2007, 01:06 PM
by
Jerald Carter