【发布时间】:2010-11-13 04:55:20
【问题描述】:
有没有办法让我的代码以不同的用户身份运行?
我正在通过 PInvoke 调用 NetUserSetInfo,我需要以其他用户的身份调用它。有没有办法做到这一点?
【问题讨论】:
标签: c# impersonation windows-authentication
有没有办法让我的代码以不同的用户身份运行?
我正在通过 PInvoke 调用 NetUserSetInfo,我需要以其他用户的身份调用它。有没有办法做到这一点?
【问题讨论】:
标签: c# impersonation windows-authentication
【讨论】:
模拟需要调用一些本机 API(即 LogonUser),因此可能不值得发布 3 页包装器代码。此页面有一个完整的工作示例:http://platinumdogs.wordpress.com/2008/10/30/net-c-impersonation-with-network-credentials/
请注意,模拟具有重要的安全考虑。确保遵循最佳做法。
【讨论】:
article 解释得很简洁:
这是文章中的代码 sn-p:
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();
【讨论】: