Windows Impersonation from C#

How can a C# program running as LocalSystem impersonate the login identity of another user temporarily? Roughly speaking I have a Windows Service that I'd like to run as LocalSystem but at times impersonate user XYZ (when connecting to a db using windows integrated security).

Most important of all: Is there a way to do this without knowing the other user's password?

Note: if a password is mandatory is there a recommended strategy for storing a password securely (c# and/or vbscript).


It's possible, although it requires you to do a lot of code. See NtCreateToken and CreateToken. You need SeCreateTokenPrivilege, although that won't be a problem since you're running under NT AUTHORITY\SYSTEM. You can then use the created token to impersonate inside a thread.


Short answer: you can't without the user password or the user calling your service through COM.

To impersonate another user in your process, you have to call ImpersonateLoggedOnUser. ImpersonateLoggedOnUser requires a token handle. There are several ways you can obtain token handle:

  • by logging on as the user with LogonUser. This however requires you to know the user password.
  • by duplicating an existing token with CreateRestrictedToken, DuplicateToken, or DuplicateTokenEx.
  • by opening the token from another process or thread, that already is loggen on as the user, with OpenProcessToken or OpenThreadToken