2013-05-15 105 views
12

我正在嘗試確定AD中的用戶帳戶是否已啓用。爲此,我使用下面的代碼:爲什麼UserPrincipal.Enabled返回不同的值?

string domain = "my domain"; 
string group = "my security group"; 
string ou = "my OU"; 

//init context 
using (var cnt= new PrincipalContext(ContextType.Domain, domain)) 
{ 
    //find the necessary security group 
    using (GroupPrincipal mainGroup 
       = GroupPrincipal.FindByIdentity(cnt, IdentityType.Guid, group)) 
    { 
     if (mainGroup != null) 
     { 
      //get the group's members 
      foreach (var user in mainGroup.GetMembers() 
            .OfType<UserPrincipal>() 
            .Where(u => u.DistinguishedName.Contains(ou))) 
      { 
       //ensure that all the info about the account is loaded 
       //by using FindByIdentity as opposed to GetMembers 
       var tmpUser= UserPrincipal.FindByIdentity(cnt, 
                  user.SamAccountName); 
       //actually I could use `user` variable, 
       //as it gave the same result as `tmpUser`. 

       //print the account info 
       Console.WriteLine(tmpUser.Name + "\t" + 
            tmpUser.Enabled.HasValue + "\t" + 
            tmpUser.Enabled.Value);      
      } 
     } 
    } 
} 

問題是,當我下的管理帳戶運行這段代碼,我得到了真正的結果,而當我在一個非priviledged帳戶運行它,user.Enabled回報false對於一些帳戶,它應該是true

唯一相似q &一個我設法找到有

  1. UserPrincipal.Enabled returns False for accounts that are in fact enabled?
  2. Everything in Active Directory via C#.NET 3.5 (Using System.DirectoryServices.AccountManagement)

不幫助這裏。

這是爲什麼?我可以選擇在非特權帳戶下獲取此信息嗎?


下面是另一種方法:How to determine if user account is enabled or disabled

private bool IsActive(DirectoryEntry de) 
{ 
    if (de.NativeGuid == null) 
     return false; 

    int flags = (int)de.Properties["userAccountControl"].Value; 

    if (!Convert.ToBoolean(flags & 0x0002)) 
     return true; 
    else 
     return false; 
} 

相同的方法在Active Directory Objects and C#進行說明。

但是,當在無特權用戶帳戶下運行時,userAccountControl屬性爲null,並且無法確定帳戶的狀態。


這裏的解決方法是使用PrincipalContext Constructor,指定具有足夠權限的用戶的憑證來訪問AD。

它對我來說依然不清楚,爲什麼無特權用戶完全可以訪問AD,並且無法獲取某些特定帳戶屬性的值。可能這與C#無關,應該在AD中配置...

回答

1

您需要爲將要執行AD查詢的帳戶委派Active Directory中的權限。這就是我必須爲我的應用程序工作(儘管我們正在用戶帳戶上執行其他管理任務)。

檢查Here以獲取有關如何委派權限的說明(或參見下面的blockquote)。

您可以稱之爲以下步驟運行代表團:

  • 通過執行以下步驟啓動控制委派嚮導:
    • 打開Active Directory用戶和計算機。
    • 在控制檯樹中,雙擊域節點。
    • 在詳細信息菜單中,右鍵單擊組織單位,單擊委託控制,然後單擊下一步。
    • 選擇您想要委派常用管理任務的用戶或組。爲此,請執行以下步驟:
    • 在用戶或組頁面上,單擊添加。
    • 在選擇用戶,計算機或組中,寫下您必須委派組織單位控制權的用戶和組的名稱,單擊確定。然後點擊下一步。
    • 將常見任務分配給委託。爲此,請執行以下常見任務。
    • 在要分頁的任務上,單擊委派以下常見任務。
    • 在委派頁面的任務上,選擇要委派的任務,然後單擊確定。單擊Finish

例如:要委派管理員移動用戶/計算機對象,您可以使用AD用戶和計算機超前模式和運行代表團。它應該在兩個OU中都有寫入權限,以便移動對象。對於寫入新值,管理員帳戶應具有委派的用戶帳戶值(在特定的OU完全權限也是如此。

別的東西值得研究的是,如果賬戶有userAccountControl屬性。我聽說在大多數情況下,這個屬性應該設置爲NormalAccount

+0

如果你可以從你的鏈接添加確切的指令,你的答案會更好,更安全的鏈接破壞 – ForceMagic

+1

謝謝。從鏈接添加相關信息的blockquote。 –

相關問題