为什么UserPrincipal.Enabled返回不同的值?

hor*_*rgh 12 c# active-directory

我正在尝试确定是否启用了AD中的用户帐户.为此,我使用以下代码:

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);                    
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,当我在管理帐户下运行此代码时,我得到了真实的结果,而当我在非特权帐户下运行它时,user.Enabled返回false一些帐户,而它应该是true.

我设法找到的唯一类似的q&a是

  1. 对于实际启用的帐户,UserPrincipal.Enabled返回False?
  2. 通过C#.NET 3.5在Active Directory中的所有内容(使用System.DirectoryServices.AccountManagement)

在这里没有帮助.

为什么会这样?我可以选择在非特权帐户下获取此信息吗?


这是另一种方法:如何确定是启用还是禁用用户帐户:

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;
}
Run Code Online (Sandbox Code Playgroud)

Active Directory对象和C#中描述了相同的方法.

但是,当在未经授权的用户帐户下运行时,userAccountControl属性是null,并且无法确定帐户的状态.


此处的解决方法是使用PrincipalContext构造函数,指定具有足够权限的用户的凭据以访问AD.

我不清楚,为什么没有特权的用户完全可以访问AD,并且无法获得某些特定帐户属性的值.可能这与C#无关,应该在AD中配置...

Tyl*_*ngs 1

您需要在 Active Directory 中为将执行 AD 查询的帐户委派权限。这是我必须做的才能使我的应用程序正常工作(尽管我们正在对用户帐户执行其他管理任务)。

检查此处以获取有关如何委派权限的说明(或参见下面的块引用)。

您可以参考以下流程进行委托:

  • 通过执行以下步骤启动控制委派向导:
    • 打开 Active Directory 用户和计算机。
    • 在控制台树中,双击域节点。
    • 在详细信息菜单中,右键单击组织部门,单击委派控制,然后单击下一步。
    • 选择您想要向其委派常见管理任务的用户或组。为此,请执行以下步骤:
    • 在“用户或组”页面上,单击“添加”。
    • 在选择“用户、计算机或组”中,写入您必须向其委派组织单位控制权的用户和组的名称,然后单击“确定”。然后单击下一步。
    • 将共同任务分配给委派。为此,请执行以下常见任务。
    • 在要委派的任务页面上,单击委派以下常见任务。
    • 在“要委派的任务”页面上,选择要委派的任务,然后单击“确定”。单击“完成”

例如:要委派管理员移动用户/计算机对象,您可以在 AD 用户和计算机中使用高级模式并运行委派。它应该在两个 OU 中都具有用于移动对象的写入权限。要写入新值,管理员帐户应在用户帐户上拥有委派值(以及特定 OU 中的完全权限。

其他值得研究的事情是帐户是否具有 userAccountControl 属性。我听说缺少此属性的帐户可能无法正确报告。在大多数情况下,此属性应设置为 NormalAccount。