简体   繁体   中英

IsInRole always returns “User” for account type “Administrator”

I'm using the following code to test if the current user has administrator rights:

WindowsIdentity winIdentity = WindowsIdentity.GetCurrent();
WindowsPrincipal winPrincipal = new WindowsPrincipal(winIdentity);

return (winPrincipal.IsInRole("Administrator") || 
   winPrincipal.IsInRole("BUILTIN\\Administrators") ||
   winPrincipal.IsInRole(WindowsBuiltInRole.Administrator) || 
   winPrincipal.IsInRole(WindowsBuiltInRole.PowerUser));

Somehow, this always return False (no administrator).

The user, I'm testing with, has the Account Type "Administrator" (testing on Windows 8.1/64 and Windows 2008/64).

What am I missing here?

Even if the account is an administrator type, that does not mean that the current role will be that of an administrator. This is purely for protection so that you are not constantly running everything with full permissions as an administrator.

The technology is called User Account Control or UAC in short, and is Microsoft's way of dealing with the access protection for administrator accounts.

So if you get the result that you are not in the role of an administrator, then you are not running the process while elevated to administrator permissions. You can usually change that by right-clicking and choosing “Run as administrator”.

If you want to start it from Visual Studio, you can run VS as an administrator to make the programs you are debugging elevated too.

Finally, when using the string overload of IsInRole you should check for BUILTIN\\Administrators instead of just Administrator . The better solution would be to use the WindowsBuiltInRole overload though.

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