Authenticating Domain Users with System.DirectoryServices

大憨熊 提交于 2019-12-08 23:58:38

问题


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


回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/30861/authenticating-domain-users-with-system-directoryservices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!