Check if the current user is an administrator

My application needs to run some scripts, and I have to be sure that the user executing them is the administrator ... What is the best way to do this using C #?

+66
c #
Aug 30 '10 at 12:34
source share
6 answers
using System.Security.Principal; public static bool IsAdministrator() { using (WindowsIdentity identity = WindowsIdentity.GetCurrent()) { WindowsPrincipal principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); } } 
+80
Aug 30 '10 at 12:36
source share
 return new WindowsPrincipal(WindowsIdentity.GetCurrent()) .IsInRole(WindowsBuiltInRole.Administrator); 
+27
Aug 30 '10 at 12:36
source share

You can also call the Windows API:

 [DllImport("shell32.dll", SetLastError=true)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool IsUserAnAdmin(); 

which tells you in more detail whether the user is working under elevated privileges.

+6
Dec 12 '16 at 22:24
source share

The above answers with IsInRole are really correct: it checks to see if the current user has administrator rights. However,

Starting with Windows Vista, User Account Control (UAC) defines user privileges. If you are a member of the Embedded Admins group, you are assigned two access tokens at run time: the standard user access token and the administrator access token. By default, you are the standard user.

(from MSDN, for example, https://msdn.microsoft.com/en-us/library/system.diagnostics.eventlogpermission(v=vs.110).aspx )

Thus, IsInRole defaults to user privileges, and thus the method returns false. True, only if the program is explicitly run as administrator.

Another method for checking AD at https://ayende.com/blog/158401/are-you-an-administrator will check if the username is in the administrators group.

My complete method combining both:

  public static bool IsCurrentUserAdmin(bool checkCurrentRole = true) { bool isElevated = false; using (WindowsIdentity identity = WindowsIdentity.GetCurrent()) { if (checkCurrentRole) { // Even if the user is defined in the Admin group, UAC defines 2 roles: one user and one admin. // IsInRole consider the current default role as user, thus will return false! // Will consider the admin role only if the app is explicitly run as admin! WindowsPrincipal principal = new WindowsPrincipal(identity); isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator); } else { // read all roles for the current identity name, asking ActiveDirectory isElevated = IsAdministratorNoCache(identity.Name); } } return isElevated; } /// <summary> /// Determines whether the specified user is an administrator. /// </summary> /// <param name="username">The user name.</param> /// <returns> /// <c>true</c> if the specified user is an administrator; otherwise, <c>false</c>. /// </returns> /// <seealso href="https://ayende.com/blog/158401/are-you-an-administrator"/> private static bool IsAdministratorNoCache(string username) { PrincipalContext ctx; try { Domain.GetComputerDomain(); try { ctx = new PrincipalContext(ContextType.Domain); } catch (PrincipalServerDownException) { // can't access domain, check local machine instead ctx = new PrincipalContext(ContextType.Machine); } } catch (ActiveDirectoryObjectNotFoundException) { // not in a domain ctx = new PrincipalContext(ContextType.Machine); } var up = UserPrincipal.FindByIdentity(ctx, username); if (up != null) { PrincipalSearchResult<Principal> authGroups = up.GetAuthorizationGroups(); return authGroups.Any(principal => principal.Sid.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid) || principal.Sid.IsWellKnown(WellKnownSidType.AccountDomainAdminsSid) || principal.Sid.IsWellKnown(WellKnownSidType.AccountAdministratorSid) || principal.Sid.IsWellKnown(WellKnownSidType.AccountEnterpriseAdminsSid)); } return false; } 

For a user in the administrator group without elevated privileges (UAC is enabled), this IsCurrentUserAdmin () method returns! CheckCurrentRole: true if checkCurrentRole == false, but false if checkCurrentRole == true.

If you run code that REQUIRES administrator privileges, consider checkCurrentRole == true. Otherwise, you will receive a security exception by then. Therefore, the correct logic is IsRole .

+6
Jun 15 '17 at 10:47 on
source share

Just thought I'd add another solution; since IsInRole does not always work.

  • If the user is not a member of the specified Windows user group in the current session.
  • Admin Changes Group Policy Settings
  • The role parameter is considered as case sensitive.
  • And if on a computer with XP there is no installed version of the .NET Framework, this will not work.

Depending on your needs, if you need to support old systems; or not sure how your client physically controls your system. This is the solution I implemented; for flexibility and change.

 class Elevated_Rights { // Token Bool: private bool _level = false; #region Constructor: protected Elevated_Rights() { // Invoke Method On Creation: Elevate(); } #endregion public void Elevate() { // Get Identity: WindowsIdentity user = WindowsIdentity.GetCurrent(); // Set Principal WindowsPrincipal role = new WindowsPrincipal(user); #region Test Operating System for UAC: if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major < 6) { // False: _level = false; // Todo: Exception/ Exception Log } #endregion else { #region Test Identity Not Null: if (user == null) { // False: _level = false; // Todo: "Exception Log / Exception" } #endregion else { #region Ensure Security Role: if (!(role.IsInRole(WindowsBuiltInRole.Administrator))) { // False: _level = false; // Todo: "Exception Log / Exception" } else { // True: _level = true; } #endregion } // Nested Else 'Close' } // Initial Else 'Close' } // End of Class. 

Thus, the above code has several constructs; it really checks to see if the user will be on Vista or higher. Thus, if the client is on XP without a frame or beta from several years ago, this will allow you to change what you want to do.

He will then physically check to avoid a null value for the account.

Then, in the end, he will provide a check to make sure that the user is indeed in the proper role.

I know that the question was answered; but I thought my solution would be a great addition to the page for anyone looking for a Stack. My discussion of the Protected constructor will allow you to use this class as a Derived class that you could monitor when the class is instantiated.

+2
Dec 20
source share

I must be sure that the user executing them is the administrator

If your application should be run with administrator privileges, it would be correct to update its manifest.
Set requestedExecutionlevel to requireAdminstrator .

0
May 31 '17 at 10:01
source share



All Articles