Recent Posts

Monday, August 17, 2009

How to login as different windows user from vb.net application

I was just doing a vb net application that talks to a third party application that runs under a windows service domain user account.

So now my application need to login as the service account from the vb net code and then talk to the third party application and then log off from the service account.

I have solved this using the below visual basic code

Imports System.Security.Principal

Module Common
Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As String, _
ByVal lpszDomain As String, _
ByVal lpszPassword As String, _
ByVal dwLogonType As Integer, _
ByVal dwLogonProvider As Integer, _
ByRef phToken As IntPtr) As Integer

Declare Auto Function DuplicateToken Lib "advapi32.dll" _
(ByVal ExistingTokenHandle As IntPtr, _
ByVal ImpersonationLevel As Integer, _
ByRef DuplicateTokenHandle As IntPtr) As Integer


Dim impersonationContext As WindowsImpersonationContext
Dim LOGON32_LOGON_INTERACTIVE As Integer = 2
Dim LOGON32_PROVIDER_DEFAULT As Integer = 0

Public Function impersonateValidUser(ByVal userName As String, _
ByVal domain As String, ByVal password As String) As Boolean

Dim tempWindowsIdentity As WindowsIdentity
Dim token As IntPtr
Dim tokenDuplicate As IntPtr

If LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, _
LOGON32_PROVIDER_DEFAULT, token) <> 0 Then
If DuplicateToken(token, 2, tokenDuplicate) <> 0 Then
tempWindowsIdentity = New WindowsIdentity(tokenDuplicate)
impersonationContext = tempWindowsIdentity.Impersonate()
If impersonationContext Is Nothing Then
impersonateValidUser = False
Else
impersonateValidUser = True
End If
Else
impersonateValidUser = False
End If
Else
impersonateValidUser = False
End If
End Function

Public Sub undoImpersonation()
impersonationContext.Undo()
End Sub

End Module


Now call the function as below to Sign ON

Private Sub SignOn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SignOn.Click

If impersonateValidUser("test", "", "test") Then
' do talking to the third party application here


Else
MsgBox("The user is not validated")
End If

End Sub


Now call the function as below to Sign OFF

Private Sub SignOff_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SignOff.Click
undoImpersonation()

End Sub


Read more!