tags:

views:

451

answers:

4

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?

+1  A: 

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

http://stackoverflow.com/questions/45437/determining-members-of-local-groups-via-c#45458

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);
}
Espo
The System.DirectoryServices.AccountManagement namespace is new to .NET 3.5, isn't it?
Marek Grzenkowicz
First sentence in the linked article:"Looking through some of the new 3.5 stuff I stumbled over a new assembly named "System.DirectoryServices.AccountManagement" - that caught my attention."
Espo
Sorry, I missed it.Could you add information CheckTokenMembership to your answer to make it complete (so I can mark it as accepted answer)?
Marek Grzenkowicz
+1  A: 

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)

Anders
+1  A: 

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

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

Rob Walker
"IsUserAnAdmin function is a wrapper for CheckTokenMembership. It is recommended to call that function directly to determine Administrator group status rather than calling IsUserAnAdmin". (From the linked page)
Espo
I hadn't noticed the warning before. I wonder why Microsoft would consider deprecating such a simpler helper ... fortunately they have a good track record for backwards compatibility.
Rob Walker
The IsUserAnAdmin() function can only be used to check the _current_ user, so I cannot use it.
Marek Grzenkowicz
A: 

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.

Ryan