There can be at least four different identities involved at this point:
- The identity assigned to the thread
- The identity assigned to the process
- The account of the user who started the process
- The account of the user who logged onto the PC
In your code you're getting (1). This is normally fine, and is usually the same as (2).
To retrieve (2), you could:
- Call
WindowsIdentity.GetCurrent
to get the impersonated identity
- Undo impersonation by calling the Win32
RevertToSelf
function
- Look at
WindowsIdentity.GetCurrent
to get the underlying process identity
- Reset the thread identity by impersonating the identity from step (1)
(2) and (3) will be the same unless you've written unmanaged code that changes the process identity. As @Daniel points out, (3) and (4) could legitimately be different in the presence of the Windows "run as" command.
Edit: You can trust that the current WindowsIdentity
is who it says it is, insofar as you can trust any given piece of data in your application.
You could spoof it by attaching a debugger to your process and faking the return value from this call, but if you're going to do that, you might as well fake the piece of code where you pass the user name to the database.
The 100% safe way to do this is to use integrated authentication/SSPI to connect to the database.