Simple Impersonation Library for .Net
This library provides a managed wrapper for the LogonUser function of the Win32 API. Basically, it allows you to impersonate any user, as long as you have their credentials.
It is dual compiled for both .Net 2.0 and .Net 4.0 runtimes. It should work well under .Net 2.0, 3.0, 3.5, 4.0, 4.5, and the client profiles. It has no dependencies.
Use NuGet package SimpleImpersonation.
PM> Install-Package SimpleImpersonation
using (Impersonation.LogonUser(domain, username, password, logonType))
{
// do whatever you want as this user.
}
Be sure to specify a logon type that makes sense for what you are doing. For example:
-
If you are interactively working as a particular user from a desktop application, use
LogonType.Interactive
. -
If you are trying to connect to a SQL server with trusted authentication using specific credentials, use
LogonType.NewCredentials
.- But be aware that impersonation is not taken into account in connection pooling.
- You will also need to vary your connection string.
- Read more here
See the MSDN documentation for additional logon types.