Darryl Hoar
Darryl Hoar

Reputation: 93

how to check if current user is in admin group c#

I have read the relevant Stack Overflow questions and tried out the following code:

WindowsIdentity identity = WindowsIdentity.GetCurrent();
if (null != identity)
{
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
return false;

It does not return true even though I have manually confirmed that the current user is a member of the local built-in Administrators group.

What am I missing ?

Thanks.

Upvotes: 5

Views: 4395

Answers (2)

Alexan
Alexan

Reputation: 8625

Just found other way to check if user is admin, not running application as admin:

private static bool  IsAdmin()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            if (identity != null)
            {
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                List<Claim> list = new List<Claim>(principal.UserClaims);
                Claim c = list.Find(p => p.Value.Contains("S-1-5-32-544"));
                if (c != null)
                    return true;
            }
            return false;
        }

Credit to this answer, but code is corrected a bit.

Upvotes: 5

Rufus L
Rufus L

Reputation: 37020

The code you have above seemed to only work if running as an administrator, however you can query to see if the user belongs to the local administrators group (without running as an administrator) by doing something like the code below. Note, however, that the group name is hard-coded, so I guess you would have some localization work to do if you want to run it on operating systems of different languages.

using (var pc = new PrincipalContext(ContextType.Domain, Environment.UserDomainName))
{
    using (var up = UserPrincipal.FindByIdentity(pc, WindowsIdentity.GetCurrent().Name))
    {
        return up.GetAuthorizationGroups().Any(group => group.Name == "Administrators");
    }
}

Note that you can also get a list of ALL the groups the user is a member of by doing this inside the second using block:

var allGroups = up.GetAuthorizationGroups();

But this will be much slower depending on how many groups they're a member of. For example, I'm in 638 groups and it takes 15 seconds when I run it.

Upvotes: 4

Related Questions