Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Authentication in .NET

Tags:

c#

.net

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

like image 261
Denis Avatar asked Feb 01 '12 22:02

Denis


2 Answers

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

like image 85
Gabriel GM Avatar answered Sep 30 '22 19:09

Gabriel GM


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
like image 45
Denis Avatar answered Sep 30 '22 19:09

Denis