Question

I am trying to have a method that takes in a username and will return true if that user is a local administrator (not on the entire domain, just the local machine) and false otherwise. I've tried to change the technique found at In .NET/C# test if process has administrative privileges to work, but it did not. I have tried using the NetUserGetInfo way, but could not get that to work. Now I'm trying to use UserPrincipal. The below code is all that I have...mainly just testing that the basics worked and they do.

PrincipalContext ctx = new PrincipalContext(ContextType.Machine);
UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userId);

if(usr == null)
{
    Console.WriteLine("usr is null");
}
else
{
    Console.WriteLine(usr.Enabled);
    Console.WriteLine(usr.IsAccountLockedOut());

    foreach (Principal p in usr.GetAuthorizationGroups())
    {
        Console.WriteLine(p.ToString());   
    }
}

It looks like I should be able to use the isMemberOf method, but how do I make a Group for the local administrators? Or is there a better way than the isMemberOf method?

Was it helpful?

Solution

Well actually I am able to just check if one of the Principals returned from GetAuthorizationGroups()) is equal to "Administators".

foreach (Principal p in usr.GetAuthorizationGroups())
{
    if (p.ToString() == "Administrators")
    {
        result = true;
    }
}

OTHER TIPS

Another possibility. If you get the WindowsIdentity from the UserPrincipal object. You can use the IsInRole(groupname) method.

You can get the WindowsIdentity by doing

var identity = new WindowsIdentity(string sUserPrincipalName);

// then use this method to check the Identity against any Active Directory group.
public static bool UserIsInRole(WindowsIdentity identity, string group)
{
    try
    {
        return new WindowsPrincipal(identity).IsInRole(group);
    }
    catch (Exception ex)
    {
        //Error checking role membership
        return false;
    }
}

This'll do it

    static bool IsAdmin()
    {
        // net localgroup administrators

        var proc = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = "net",
                Arguments = "localgroup administrators",
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            }
        };

        proc.Start();

        var computer = new PrincipalContext(ContextType.Machine).ConnectedServer;
        var isAdmin = proc.StandardOutput.ReadToEnd().Contains(computer);

        return isAdmin;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top