我有一个.NET应用程序(混合了C#和VB.NET),我想显示一个Windows登录对话框(或我的自定义对话框)并使用Windows身份验证来认证用户。根据要求,我需要在至少一分钟的闲置后要求用户进行身份验证。我更喜欢使用.NET本机方式进行Windows身份验证,但也对其他方式感兴趣...
要对用户进行身份验证,您可以使用PrincipalContext的ValidateCredential方法。请确保添加引用System.DirectoryServices.AccountManagement
。
//If you are validating on a domain
PrincipalContext pcon = new PrincipalContext(ContextType.Domain);
if(pcon.ValidateCredential(txtUsername.Text,
txtPassword.Text,
ContextOptions.Negotiate))
{
//User is authenticated
}
如果您不是根据域名进行验证,请检查其他ContextType
。您也可以使用其他选项来验证凭据(ContextOptions
)。
我发现了以下内容,并且为了完整性考虑决定添加。我仍然喜欢Gabriel的答案!
Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As String, ByVal lpszDomain As String, ByVal lpszPassword As String, ByVal dwLogonType As LogonType, ByVal dwLogonProvider As Integer, ByRef phToken As IntPtr) As Integer
Private Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal hObject As IntPtr) As Boolean
Public Enum LogonType As Integer
LOGON32_LOGON_INTERACTIVE = 2
LOGON32_LOGON_NETWORK = 3
LOGON32_LOGON_BATCH = 4
LOGON32_LOGON_SERVICE = 5
LOGON32_LOGON_UNLOCK = 7
LOGON32_LOGON_NETWORK_CLEARTEXT = 8
LOGON32_LOGON_NEW_CREDENTIALS = 9
End Enum
Public Function IsAuthenticated(ByVal Username As String, ByVal Password As String, Optional ByVal Domain As String = "") As Boolean
Dim Token As New IntPtr
LogonUser(Username, Domain, Password, LogonType.LOGON32_LOGON_INTERACTIVE, 0, Token)
CloseHandle(Token)
If Token.ToInt32 <> 0 Then Return True
End Function