Run Code as a different user
Asked Answered
N

3

40

Is there a way to tell my code to run as a different user?

I am calling NetUserSetInfo via a PInvoke and I need to call it as a different user. Is there a way to do that?

Nucleon answered 22/7, 2009 at 22:7 Comment(0)
H
30

Impersonation requires calling some native APIs (namely, LogonUser) so it's probably not worth posting 3 pages of wrapper code. This page has a complete working sample: http://platinumdogs.wordpress.com/2008/10/30/net-c-impersonation-with-network-credentials/

Note that impersonation has important security considerations. Make sure you follow best practices.

Harrovian answered 22/7, 2009 at 22:17 Comment(0)
I
31

Probably the best and the cleanest code that I have seen so far is this:

var credentials = new UserCredentials(domain, username, password);
Impersonation.RunAsUser(credentials, logonType, () =>
{
    // do whatever you want as this user.
});

Just follow Github or Nuget.

Infidelity answered 26/5, 2015 at 18:48 Comment(1)
This certainly was easy to implement but I can't validate that it is working. I do a process.start("cmd.exe") and the process still shows as owned by the ID that started the program not the impersonated ID. What could I be missing?Anthesis
H
30

Impersonation requires calling some native APIs (namely, LogonUser) so it's probably not worth posting 3 pages of wrapper code. This page has a complete working sample: http://platinumdogs.wordpress.com/2008/10/30/net-c-impersonation-with-network-credentials/

Note that impersonation has important security considerations. Make sure you follow best practices.

Harrovian answered 22/7, 2009 at 22:17 Comment(0)
L
11

This article explains it pretty succinctly:

Here's a code snippet from the article:

IntPtr accessToken = IntPtr.Zero;
....
//You have to initialize your accessToken with API calling 
....
WindowsIdentity identity = new WindowsIdentity(accessToken);
WindowsImpersonationContext context = identity.Impersonate();
...
// Now your code is using the new WindowsLogin and you can do what ever this login can do
...

//Now you can return to your current login of Windows
context.Undo();
Lonnylonslesaunier answered 22/7, 2009 at 22:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.