.NET中的Windows身份验证

本文关键字:身份验证 Windows 中的 NET | 更新日期: 2023-09-27 18:22:05

我有一个.NET应用程序(C#和VB.NET的混合),我想在其中显示Windows登录对话框(或我自己的对话框),并使用Windows身份验证对用户进行身份验证。根据要求,我需要在空闲至少一分钟后要求用户进行身份验证。我更喜欢.NET本机方式来进行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