Run Code as a different user

2019-01-03 10:12发布

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?

4条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-03 10:20

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

using (Impersonation.LogonUser(domain, username, password, logonType))
{
    // do whatever you want as this user.
}

Just follow Github or Nuget.

查看更多
唯我独甜
3楼-- · 2019-01-03 10:21

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();
查看更多
聊天终结者
4楼-- · 2019-01-03 10:24

Yes Impersonation does help to run some code as different user. It works fine in my case. ( Thanks to Milan Matějka)

I also found a Ref link. Hope it will help you get the package from nuget easily : http://iamfixed.blogspot.de/2017/11/run-code-as-different-user-in-c-from.html

查看更多
淡お忘
5楼-- · 2019-01-03 10:32

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.

查看更多
登录 后发表回答