2010-08-30 95 views

回答

72
using System.Security.Principal; 

public static bool IsAdministrator() 
{ 
    WindowsIdentity identity = WindowsIdentity.GetCurrent(); 
    WindowsPrincipal principal = new WindowsPrincipal(identity); 
    return principal.IsInRole(WindowsBuiltInRole.Administrator); 
} 
+4

只需注意,如果在Vista或Win7中启用UAC,上述操作将不起作用;在这种情况下,您需要弹出一个UAC确认框并提升权限。 – MisterZimbu 2010-08-30 13:34:15

+0

关于http://ayende.com/blog/158401/are-you-an-administrator或http://blogs.msdn.com/b/jaredpar/archive/2007/08/01/detecting-if-you -are-an-admin.aspx?哪种方法更好? – Kiquenet 2014-08-28 12:26:46

+2

对我而言不起作用FY.I我是管理员 – 2016-07-14 09:33:23

25
return new WindowsPrincipal(WindowsIdentity.GetCurrent()) 
    .IsInRole(WindowsBuiltInRole.Administrator); 
+2

@Nissim:两种极端都可能不好,但我们需要根据具体情况进行判断。 – 2010-08-30 12:43:06

+32

@Nissm:你们都同时回答,或者接近5分钟后你们都列为“5分钟前”。你没有理由攻击Alex;我们不是为了赢得代表,我们来帮忙。 – Randolpho 2010-08-30 12:44:09

+0

关于http://ayende.com/blog/158401/are-you-an-administrator或http://blogs.msdn.com/b/jaredpar/archive/2007/08/01/detecting-if-you -are-an-admin.aspx?哪种方法更好? – Kiquenet 2014-08-28 12:28:30

2

只是觉得我想补充另一种解决方案;因为IsInRole并不总是有效。

  • 如果用户不是当前会话中指定的Windows用户组的成员。
  • 管理员已对组策略设置进行了更改
  • 角色参数被视为“区分大小写”方法。
  • 如果XP机器没有安装.NET Framework版本,它将不起作用。

根据您的需要,如果您需要支持旧系统;或者不确定您的客户如何实际管理您的系统。这是我实施的解决方案;灵活性和改变。

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. 

所以上面的代码有几个结构;它会实际测试以查看用户是否在Vista或更高版本上。这样,如果客户在几年前没有框架或beta框架的情况下使用XP,它将允许您更改您想要执行的操作。

然后它将进行物理测试以避免帐户的空值。

最后,它将提供检查以验证用户是否确实处于正确的角色。

我知道这个问题已经回答了;但是我认为我的解决方案对于搜索Stack的其他人来说是一个很好的补充。我在Protected Constructor背后的推理将允许您将此类用作派生类,您可以控制该类实例化时的状态。

+0

关于http://ayende.com/blog/158401/are-you-an-administrator或http://blogs.msdn.com/b/jaredpar/archive/2007 /08/01/detecting-if-you-are-an-admin.aspx?哪种方法更好? – Kiquenet 2014-08-28 12:27:51

5

您也可以调用Windows API来做到这一点:

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

这更一般地告诉你用户是否在提升的权限运行。

0

我必须确保运行它们的用户是管理员

如果您的应用程序必须拥有管理员权限下运行,这将是正确的,更新其清单。
Set requestedExecutionlevel to requireAdminstrator

1

IsInRole以上的答案是实际上是正确的:它检查当前用户具有管理员权限。 但是,

从Windows Vista开始,用户帐户控制(UAC)将确定用户的权限。如果您是内置管理员组的成员,则会为您分配两个运行时访问令牌:标准用户访问令牌和管理员访问令牌。默认情况下,您处于标准用户角色。

(从MSDN,例如https://msdn.microsoft.com/en-us/library/system.diagnostics.eventlogpermission(v=vs.110).aspx

因此,IsInRole每默认将考虑用户权限,并且因此该方法返回false。只有当软件以管理员身份明确运行时才是如此。

另一种方法检查AD https://ayende.com/blog/158401/are-you-an-administrator将检查用户名是否在管理员组中。

我的完整方法结合两种是这样的:

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; 
    } 

对于管理员组中的用户没有提升的权限(启用UAC),这种方法IsCurrentUserAdmin()返回checkCurrentRole:真要是checkCurrentRole ==假的,但假如checkCurrentRole == true

如果您运行的代码需要管理员权限,请考虑checkCurrentRole == true。否则,到那时你会得到一个安全异常。因此正确的IsInRole逻辑。

相关问题