C# 以其他用户身份运行代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1168571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:53:05  来源:igfitidea点击:

Run Code as a different user

c#impersonationwindows-authentication

提问by Vaccano

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?

我通过 PInvoke 调用 NetUserSetInfo,我需要以不同的用户身份调用它。有没有办法做到这一点?

采纳答案by Richard Berg

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/

模拟需要调用一些本机 API(即 LogonUser),因此可能不值得发布 3 页的包装器代码。此页面有一个完整的工作示例: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.

请注意,模拟具有重要的安全考虑。确保您遵循最佳实践。

回答by JohnFx

This articleexplains 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();

回答by Milan Matějka

Probably the best and the cleanest codethat 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 Githubor Nuget.

只需关注GithubNuget 即可