I am using C# and .Net Framework 4.
I am looking for a foolproof method to get the login id of the currently logged in windows user that is not susceptible to impersonation or hacking. I am looking for this in the form of: DOMAINNAME\USERNAME
e.g. SOMEDOMAIN\JohnDoe
Currently the best I have is:
var identity = System.Security.Principal.WindowsIdentity.GetCurrent();
var currentLoginId = identity.Name;
Is this open to impersonation (outside of someone knowing both the username and password) and if so is there a better way of doing this?
There can be at least four different identities involved at this point:
In your code you're getting (1). This is normally fine, and is usually the same as (2).
To retrieve (2), you could:
WindowsIdentity.GetCurrent
to get the impersonated identityRevertToSelf
functionWindowsIdentity.GetCurrent
to get the underlying process identity(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.
Only a partial answer:
I believe
System.Security.Principal.WindowsIdentity.GetCurrent();
will return the windows user account associaed with the currently executing thread. If the thread or application was started under a different user account from the logged in user, you won't get what you're after using this.If you can be sure that your aplication was not started using the "run-as" feature (or programatic equialent) and you're not doing anything internally with respect to the thread's identity, you can probably be sure this is the logged in user's account but I'm not 100% on this.
It may be possible to find the user account associated with the widows "session" within which the application is running by using ADSI (see System.DirectoryServices).