How to check if a given user is a member of the bu

2020-03-30 03:32发布

I need to check programmatically (in .NET) whether a given user (domain account) is a member of the built-in Administrators group on a current computer (the one where the application gets executed).

Is it possible?

标签: .net security
4条回答
我只想做你的唯一
2楼-- · 2020-03-30 03:50

If you are talking about the currently running user then

using System.Security.Principal;

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

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

If not then I expect its possible to set identity to a particular user but not looked into how.

查看更多
女痞
3楼-- · 2020-03-30 03:52

I don't know about .Net, but in win32, the easy way is to call IsUserAnAdmin(). If you need more control, you can open the process token and check with CheckTokenMembership for each group you need to check

Edit: See pinvoke.net for .NET sample code (Thanks chopeen)

查看更多
Animai°情兽
4楼-- · 2020-03-30 03:52

There is a Win32 API for this you could P/Invoke: IsUserAnAdmin

The question is more complex on Vista ... see this blog post.

查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-03-30 04:02

You could loop the groups like i did in this answer:

Determining members of local groups via C#

After reading some more, the easiest thing would be to use the System.DirectoryServices.AccountManagement namespace. Here is how it can be used:

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

Sample:

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);
}
查看更多
登录 后发表回答