检查是否启用了UserPrincipal

Joh*_*ith 5 c# active-directory

我正在使用C#代码查询Active Directory。我遇到的主要问题是确定帐户是否已被禁用。通过浏览许多在线文章,似乎不能仅仅依靠属性UserPrincipal.Enabled来确定是否启用了用户帐户。相当公平,因为它是可为null的布尔值,但是当AD管理员禁用帐户时,它的确设置为false。我遇到的问题是,当我查询客户端的广告时,我发现大多数用户帐户的UserPrincipal对象为此属性返回false。因此,当我使用此代码检查帐户是否被禁用时:

private bool IsUserEnabled(UserPrincipal userPrincipal)
{
        bool isEnabled = true;

        if (userPrincipal.AccountExpirationDate != null)
        {
            // Check the expiration date is not passed.
            if (userPrincipal.AccountExpirationDate <= DateTime.Now)
            {
                Log.DebugFormat("User {0} account has expired on {1}", userPrincipal.DisplayName, userPrincipal.AccountExpirationDate.Value);
                isEnabled = false;
            }
        }

        if (userPrincipal.IsAccountLockedOut())
        {
            isEnabled = false;
            Log.DebugFormat("User {0} account is locked out", userPrincipal.DisplayName);
        }

        if (userPrincipal.Enabled != null)
        {
            isEnabled = userPrincipal.Enabled.Value;
            Log.DebugFormat("User {0} account is Enabled is set to {1}", userPrincipal.DisplayName, userPrincipal.Enabled.Value);
        }

        return isEnabled;
}
Run Code Online (Sandbox Code Playgroud)

由于userPrincipal.Enabled选中,大多数帐户似乎被禁用。

但是,如果我不考虑这个问题而仅依靠帐户到期日期和帐户锁定属性,那么我可能会错过使用Active Directory中仅禁用该帐户的复选框而被禁用的某人,而无需设置帐户到期日期。

启用返回false的所有帐户实际上都是可以登录域的活动帐户。

您如何检查帐户是否真正启用?

Tyl*_*ngs 0

我可以告诉你在我的一份应用程序中什么对我有用。这是我的应用程序的一个片段:

using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "domain.com"))
{
    using (UserPrincipal user = UserPrincipal.FindByIdentity(pc, "Doe, John"))
    {
        Console.Out.Write(user.Enabled);
    }
}
Run Code Online (Sandbox Code Playgroud)

对我来说,这可以准确地返回该帐户是否启用。

  • 我已经在我的代码中执行此操作,并且它仍然返回大多数启用的用户为 Enabled = false。使用 LDAP 浏览器,我注意到那些“启用”的用户具有 userAccountControl 属性 [NormalAccount],但那些显示为禁用的用户没有 userAccountControl 属性。 (3认同)