2013-05-15 109 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。 –

相关问题