How to authenticate against the Active Directory by using Forms Authentication
This code gives you the full detail about the authentication against AD using Forms authentication.Follow these steps:1. Add “System.DirectoryServices.dll” reference to
August 9, 2004
This code gives you the full detail about the authentication against AD using Forms authentication.
Follow these steps:
1. Add “System.DirectoryServices.dll” reference to the project.
2. Create a new class and name it as “LdapAuthentication.vb“
3. Paste the following code in that:
Imports
System
Imports
System.Text
Imports
System.Collections
Imports
System.DirectoryServices
Namespace
FormsAuthPublic Class LdapAuthenticationDim _path As StringDim _filterAttribute As StringPublic Sub New(ByVal path As String)
_path = path
End SubPublic Function IsAuthenticated(ByVal domain As String, ByVal username As String, ByVal pwd As String) As BooleanDim domainAndUsername As String = domain & "" & usernameDim entry As DirectoryEntry = New DirectoryEntry(_path, domainAndUsername, pwd)Try'Bind to the native AdsObject to force authentication. Dim obj As Object = entry.NativeObjectDim search As DirectorySearcher = New DirectorySearcher(entry)
search.Filter = "(SAMAccountName=" & username & ")"
search.PropertiesToLoad.Add("cn")
Dim result As SearchResult = search.FindOne()If (result Is Nothing) ThenReturn FalseEnd If'Update the new path to the user in the directory.
_path = result.Path
_filterAttribute =
CType(result.Properties("cn")(0), String)
Catch ex As ExceptionThrow New Exception("Error authenticating user. " & ex.Message)End TryReturn TrueEnd FunctionPublic Function GetGroups() As StringDim search As DirectorySearcher = New DirectorySearcher(_path)
search.Filter = "(cn=" & _filterAttribute & ")"
search.PropertiesToLoad.Add("memberOf")
Dim groupNames As StringBuilder = New StringBuilderTryDim result As SearchResult = search.FindOne()Dim propertyCount As Integer = result.Properties("memberOf").CountDim dn As StringDim equalsIndex, commaIndexDim propertyCounter As IntegerFor propertyCounter = 0 To propertyCount - 1
dn =
CType(result.Properties("memberOf")(propertyCounter), String)
equalsIndex = dn.IndexOf("=", 1)
commaIndex = dn.IndexOf(",", 1)
If (equalsIndex = -1) ThenReturn NothingEnd If
groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1))
groupNames.Append("|")
NextCatch ex As ExceptionThrow New Exception("Error obtaining group names. " & ex.Message)End TryReturn groupNames.ToString()End FunctionEnd Class
End
Namespace
4. Open global.asax file. Add the following lines at the top of the page
Imports
System.Web.Security
Imports
System.Security.Principal
5. Under Application_AuthenticateRequest event. add the following code:
Dim
cookieName As String = FormsAuthentication.FormsCookieNameDim authCookie As HttpCookie = Context.Request.Cookies(cookieName)If (authCookie Is Nothing) Then'There is no authentication cookie.ReturnEnd IfDim authTicket As FormsAuthenticationTicket = NothingTry
authTicket = FormsAuthentication.Decrypt(authCookie.Value)
Catch ex As Exception'Write the exception to the Event Log.ReturnEnd TryIf (authTicket Is Nothing) Then'Cookie failed to decrypt.ReturnEnd If'When the ticket was created, the UserData property was assigned a'pipe-delimited string of group names.Dim groups As String() = authTicket.UserData.Split(New Char() {"|"})'Create an Identity.Dim id As GenericIdentity = New GenericIdentity(authTicket.Name, "LdapAuthentication")'This principal flows throughout the request.Dim principal As GenericPrincipal = New GenericPrincipal(id, groups)
Context.User = principal
6. Modify the web.config file with the following changes: