Denis
Denis

Reputation: 12077

Windows Authentication in .NET

I have a .NET application (mix of C# and VB.NET) where I would like to display a Windows Login Dialog box (or my own dialog box) and authenticate the user using Windows Authentication. Per requirement, I need to ask the user to authenticate after AT LEAST a minute of being idle. I would prefer a .NET native way of doing Windows Authentication but interested in other ways...

Upvotes: 5

Views: 7977

Answers (2)

Gabriel GM
Gabriel GM

Reputation: 6639

to authenticate a user, you can use the ValidateCredential method of the PrincipalContext. Make sure to add reference 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
}

If you're not validating against a domain, check other ContextType. You can also use other option to validate the credentials (the ContextOptions).

Upvotes: 11

Denis
Denis

Reputation: 12077

Found the following and figured I'd add it for completion sake. I still like Gabriel's answer!

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

Upvotes: 2

Related Questions