FREE hit counter and Internet traffic statistics from freestats.com

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 = _
newIdentity.Impersonate()
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
File.Create("c:\windows\dan.txt")

wc.Undo() ' Done

No comments: