首页 / 知识

关于.net:如何检查给定用户是否为内置Administrators组的成员?

2023-04-14 17:15:00

关于.net:如何检查给定用户是否为内置Administrators组的成员?

How to check if a given user is a member of the built-in Administrators group?

我需要以编程方式(在.NET中)检查给定用户(域帐户)是否为当前计算机(执行应用程序的计算机)上内置Administrators组的成员。

有可能吗?


有一个Win32 API可以对此进行调用/调用:IsUserAnAdmin

在Vista上,问题更加复杂...请参阅此博客文章。


我不知道.Net,但是在win32中,简单的方法是调用IsUserAnAdmin()。如果需要更多控制,可以打开流程令牌,并为需要检查的每个组使用CheckTokenMembership进行检查

编辑:有关.NET示例代码,请参见pinvoke.net(感谢chopeen)


如果您正在谈论当前正在运行的用户,则

1
2
3
4
5
6
7
8
9
using System.Security.Principal;

WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal wp = new WindowsPrincipal(identity);

if (wp.IsInRole("BUILTIN\\Administrators"))
   // Is Administrator
else
   // Is Not

如果不是这样,我希望可以为特定用户设置身份,但没有考虑如何使用。


您可以像我在此答案中那样循环分组:

通过C#

确定本地组的成员

阅读更多内容之后,最简单的方法是使用System.DirectoryServices.AccountManagement命名空间。使用方法如下:

http://www.leastprivilege.com/SystemDirectoryServicesAccountManagement.aspx

样品:

1
2
3
4
5
6
7
8
9
10
11
12
13
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);
}

检查用户编程帐户

最新内容

相关内容

猜你喜欢