2010-08-30 90 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邏輯。

相關問題