Visual Basic.NET 7.x (2002/03)Windows 2003WebForms.NET 1.1.NET 3.0Windows 2000.NET 2.0中级开发Visual StudioWindows.NETVisual BasicASP.NET
使用 LDAP 和 ASP.NET 进行简单的 Active Directory 身份验证






4.05/5 (13投票s)
使用 LDAP 和 ASP.NET 进行快速简便的 Active Directory 身份验证
引言
我在网上到处搜索使用 VB.NET 进行 Active Directory 身份验证的方法,我找到的所有文章都使用 impersonate 模型来执行 LDAP 查询。但是,使用 System.DirectoryServices.dll 库,有一个简单的函数可以为你完成所有工作。该函数基本上接收用户名和密码,并尝试在给定的 LDAP(Active Directory)上对其进行身份验证。
背景
与其编写 20-30 行低效的代码,我希望创建一个非常短且简单的东西。此函数所做的就是尝试使用给定的凭据创建一个 LDAP 对象。如果失败,则用户名/密码组合无效。
代码
首先,你需要确保引用 System.DirectoryServices.dll。然后,使用以下代码在你的页面中包含该库:
Imports System.DirectoryServices
你可以将此函数与基于表单的身份验证一起使用,或者只是检查用户的凭据。它接受以下输入变量:
path
:AD 的 FQDN 的 LDAP 路径。例如,LDAP://mydomain.com。user
:用户的帐户名。可以加上域名作为前缀;例如,mydomain\tom 或只是 tom。pass
:用户的密码。
Function AuthenticateUser(path as String, user As String, pass As String) As Boolean
Dim de As New DirectoryEntry(path, user, pass, AuthenticationTypes.Secure)
Try
'run a search using those credentials.
'If it returns anything, then you're authenticated
Dim ds As DirectorySearcher = New DirectorySearcher(de)
ds.FindOne()
Return True
Catch
'otherwise, it will crash out so return false
Return False
End Try
End Function
该函数返回一个简单的 True
/False
,如果它使用给定的凭据成功绑定到 LDAP。
***更新*** 我添加了 AuthenticationType.Secure
以启用 Kerberos/NTLM 数据的加密,因为数据通过网络传输。我还更改了该函数,以实际搜索对象,而不是仅仅使用 NativeObject
绑定。使用更新后的代码,我已经验证没有以明文形式传递数据(使用网络监视器),并且它也可以处理使用符号的密码。