【发布时间】:2008-09-09 16:09:23
【问题描述】:
我需要以编程方式(在 .NET 中)检查给定用户(域帐户)是否是当前计算机(执行应用程序的计算机)上内置管理员组的成员。
有可能吗?
【问题讨论】:
我需要以编程方式(在 .NET 中)检查给定用户(域帐户)是否是当前计算机(执行应用程序的计算机)上内置管理员组的成员。
有可能吗?
【问题讨论】:
我不了解 .Net,但在 win32 中,简单的方法是调用 IsUserAnAdmin()。如果您需要更多控制权,您可以打开流程令牌并使用 CheckTokenMembership 检查您需要检查的每个组
编辑:请参阅pinvoke.net 获取 .NET 示例代码(感谢 Chopeen)
【讨论】:
有一个 Win32 API,您可以 P/Invoke:IsUserAnAdmin
Vista 上的问题更复杂...请参阅blog post。
【讨论】:
您可以像我在这个答案中所做的那样循环组:
Determining members of local groups via C#
阅读更多内容后,最简单的方法是使用System.DirectoryServices.AccountManagement 命名空间。以下是它的使用方法:
http://www.leastprivilege.com/SystemDirectoryServicesAccountManagement.aspx
示例:
public static bool IsUserInGroup(string username, string groupname, ContextType type)
{
PrincipalContext context = new PrincipalContext(type);
UserPrincipal user = UserPrincipal.FindByIdentity(
context,
IdentityType.SamAccountName,
username);
GroupPrincipal group = GroupPrincipal.FindByIdentity(
context, groupname);
return user.IsMemberOf(group);
}
【讨论】:
如果你说的是当前正在运行的用户,那么
using System.Security.Principal;
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal wp = new WindowsPrincipal(identity);
if (wp.IsInRole("BUILTIN\Administrators"))
// Is Administrator
else
// Is Not
如果不是,那么我希望它可以将 identity 设置为特定用户,但没有研究如何设置。
【讨论】: