Use VB.NET to impersonate a domain user

01 Aug

There are a lot of reasons you may want to pretend to be something else. Maybe you have low self esteem and need a boost. To impersonate someone or something you need a good understanding of what that thing is all about. In Windows all you need is a username and password. If you want to connect to a database with higher privlidges you can impersonate another user by right clicking SSMS and choosing “Run As”.

Web applications can impersonate other accounts by using the application pool identities. Or web applications can impersonate the connecting user by setting the identity impersonate to true in the web config.

Services such as SQL Server can run as local system or run as any domain user with the right (or wrong amount) privliges. Have you ever had a developer contact you with the error “Access denied for “DOMAINCOMPUTERNAME$”. This is because they are trying to run a program as local system on that computer and connecting to SQL on another server. You can put these AD computer accounts in a group and give the group a SQL login but I wouldn’t recommend that. What I would recommend is to use .NET to impersonate a user when accessing SQL Server.

Supply a valid username and password to AD and authentication produces something called a token. This token can be used and re-used to get at the objects you need. MSDN has some very elaborate code samples that dive very deeply into the proper methods to use the framework when it comes to impersonation. Most of these instructions were quite far over my head and way deeper down the rabbit hole than I had intended to travel. My goal was to impersonate an account that actually had very limited privlidges so I did not need all the extra tedious and bland material.

Hopefully this code sample below from MSDN that I trimmed down considerably will satisfy your taste buds.

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

Module Module1

    Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal un As String, ByVal domain As String, ByVal pw As String, ByVal LogonType As Integer, ByVal LogonProvider As Integer,  ByRef Token As IntPtr) As Boolean

    Public Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean

    Public Sub Main()
        Dim tokenHandle As New IntPtr(0)
            If LogonUser("un", "DOMAINNAME", "pw", 2, 0, tokenHandle) Then
                Dim newId As New WindowsIdentity(tokenHandle)
                Using impersonatedUser As WindowsImpersonationContext = newId.Impersonate()
                    'perform impersonated commands
                    System.IO.File.WriteAllText("C:ttestimp.txt", "test")
                End Using
                'logon failed
            End If
        Catch ex As Exception
        End Try
    End Sub
End Module

Posted by on August 1, 2011 in .NET, Network Admin


7 responses to “Use VB.NET to impersonate a domain user

  1. camellarry

    March 6, 2013 at 2:54 pm

    You rock. Thanks for this simple example. It was exactly what I needed.

  2. Marce

    May 22, 2013 at 5:44 am

    Thanks for your help, i’m running a ssis package in which I try to impersonate the user at the moment of transferring a file created from a server 1 onto a server 2 but i cant reach the server 2. The account used to impersonate is set up with attributes on the server 2 but still it wouldn’t let me go thru. Do you have any idea of how to accomplish this? i’m using your code within a ssis script task.

    By the way, the server 2 has a shared folder, lets say: \\server2\\sharedfolder\ and im using this as a domain parameter.

    Maybe i’m putting the wrong value when passing the domain parameter?

  3. BW

    October 23, 2014 at 4:14 pm

    You have a good way of thinking….:-)

  4. Mark Fergason

    May 28, 2015 at 2:47 pm

    Thank you for taking that example and simplifying! Awesome work.

    For anyone out there wondering, this works to access IBM System i (AS/400) IFS files as long as the user and password are set to match an AD account.

  5. Joana MFB

    July 27, 2016 at 3:40 am

    Thank you very much! it worked as expected. 😀

  6. Joe

    October 17, 2016 at 12:43 pm

    Was just about to give up and stumbled across your extremely informative article! Was in desperate need of this explanation/example to do almost exactly what you’ve described (access SQL server resources via ‘service/dummy’ account)

    Well done, lunch is on me!

  7. Homer

    March 1, 2017 at 1:25 pm

    This is exactly what I have been looking for. Good work. Five stars to you 🙂


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: