FREE hit counter and Internet traffic statistics from

Tuesday, June 08, 2004

Impersonating Users in .NET

I'm often asked how you impersonate a user in the .NET Framework. In an ASP.NET application it's as simple as setting the impersonate attribute of the identity element in the web.config file to true. In Windows apps its a little harder as you'll need to login as the user using a Win32 API function and then use the WindowsImpersonationContext object. Here's a class in VB .NET that you can use to get the job done.

Imports System.Runtime.InteropServices
Imports System.Security.Principal
Imports System.Security

Namespace Atomic.Security

Public Class Windows

Private Sub New()
End Sub

'Private Const NetworkLogon As Integer = 3
'Private Const DefaultLogonProvider As Integer = 0

Shared Function LogonUser(ByVal userName As String, _
ByVal userDomain As String, ByVal userPassword As String, _
ByVal logonType As Integer, ByVal logonProvider As Integer, _
ByRef token As Integer) As Boolean
End Function

Public Shared Function Impersonate(ByVal userDomain As String, _
ByVal userName As String, ByVal userPassword As String) _
As WindowsImpersonationContext
Dim token As Integer
If LogonUser(userName, userDomain, userPassword, 3, 0, token) Then
Dim impersonatedToken As New IntPtr(token)
Dim newIdentity As New WindowsIdentity(impersonatedToken)
Dim impersonationContext As WindowsImpersonationContext = _
Return impersonationContext
End If
Return Nothing
End Function
End Class
End Namespace

To use this code you could do the following:

Dim wc As WindowsImpersonationContext = Windows.Impersonate("FoxAtomic", "dfox", "password")

'Impersonate the user here to open a file

wc.Undo() ' Done

1 comment:

Anonymous said...

What do you know Metin2 gold. And do you want to know? You can get Metin2 yang here. And welcome to view our website, here you can play games, and you will get Cheap metin2 yang to play game. I know Cheap metin2 gold, and it is very interesting.Do you want a try, come and view our website, and you will learn how to Buy metin2 gold. Come and join with us. We are waiting for your coming.