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) Try 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 CloseHandle(tokenHandle) Else 'logon failed End If Catch ex As Exception 'exception End Try End Sub End Module