使用 System.DirectoryServices 对域用户进行身份验证

发布于 2024-07-04 00:48:23 字数 39 浏览 6 评论 0原文

给定域用户的用户名和密码,以编程方式验证该用户的最佳方法是什么?

Given a username and a password for a domain user, what would be the best way to authenticate that user programatically?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

转瞬即逝 2024-07-11 00:48:23

.NET 3.5 似乎添加了一个新的命名空间来处理此问题 - System.DirectoryServices.AccountManagement。 代码示例如下:

Private Function ValidateExternalUser(ByVal username As String, ByVal password As String) As Boolean
    Using context As PrincipalContext = New PrincipalContext(ContextType.Domain, _defaultDomain)
        Return context.ValidateCredentials(username, password, ContextOptions.Negotiate)
    End Using
End Function

命名空间似乎还提供了很多操作域帐户的方法(更改密码、过期密码等)。

It appears that .NET 3.5 added a new namespace to deal with this issue - System.DirectoryServices.AccountManagement. Code sample is below:

Private Function ValidateExternalUser(ByVal username As String, ByVal password As String) As Boolean
    Using context As PrincipalContext = New PrincipalContext(ContextType.Domain, _defaultDomain)
        Return context.ValidateCredentials(username, password, ContextOptions.Negotiate)
    End Using
End Function

The namespace also seems to provide a lot of methods for manipulating a domain account (changing passwords, expiring passwords, etc).

别想她 2024-07-11 00:48:23

您可以使用一些技巧来仅进行身份验证

Try
    Dim directoryEntry as New DirectoryEntry("LDAP://DomainController:389/dc=domain,dc=suffix", "username", "password")
    Dim temp as Object = directoryEntry.NativeObject
    return true
Catch
    return false
End Try

如果用户无效,则无法访问目录条目 NativeObject 并引发异常。 虽然这不是最有效的方法(异常是邪恶的,等等),但它快速且无痛。 这还有一个超酷的优势,可以与所有 LDAP 服务器一起使用,而不仅仅是 AD。

You can use some hacks to authenticate only.

Try
    Dim directoryEntry as New DirectoryEntry("LDAP://DomainController:389/dc=domain,dc=suffix", "username", "password")
    Dim temp as Object = directoryEntry.NativeObject
    return true
Catch
    return false
End Try

If the user is not valid, the directory entry NativeObject cannot be accessed and throws an exception. While this isn't the most efficient way (exceptions are evil, blah blah blah), it's quick and painless. This also has the super-cool advantage of working with all LDAP servers, not just AD.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文