简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM