【问题标题】:Getting a UserPrincipal from ADUser从 ADUser 获取 UserPrincipal
【发布时间】:2012-03-19 13:16:02
【问题描述】:

我有一个 ADUser 列表,但对于每个 ADUSER,我想获取它的属性“LastPasswordSet”,它只能通过 UserPrincipal 访问(不确定是否还有其他方式)。

如果我使用此代码,

 PrincipalContext l_objContext = new PrincipalContext(ContextType.Domain, l_strDomain, l_strUserOU);

 foreach (ADUser ADuser in Users)
            {
                UserPrincipal usr = UserPrincipal.FindByIdentity(l_objContext, ADuser.CommonName.ToString());

                if (usr.LastPasswordSet.HasValue)
                {
                    EmailString(usr.LastPasswordSet.ToString());
                }
            }

现在我不想向 UserPrincipal 提供除 ADUSER 的任何属性之外的任何东西,并且上面的代码也不起作用,问题是它发送的电子邮件很少,然后遇到它给出的某个地方并出现错误和服务停止,这可能是因为一些无效的日期(我不想修复它,只是为了让您了解我在做什么)

【问题讨论】:

  • 看来你的问题和这个类似 - stackoverflow.com/questions/2905277/…
  • 我已经检查了那个问题,但是无论如何他们都在使用 UserPrincipal 改变它的值,如果你再次阅读我的问题,它会说我如何通过使用 ADUser 属性来获取 userPrincipal ......跨度>

标签: c# .net active-directory ldap


【解决方案1】:

您可以创建自己的PrincipalContext,然后使用UserPrincipal.FindByIdentity 获取主体。从这里,我怀疑你已经知道了,你可以调用LastPasswordSet 属性。

public static DateTime? GetLastPasswordSet(string domain, string userName)
{
    using (var context = new PrincipalContext(ContextType.Domain, domain))
    {
        var userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName);
        return userPrincipal.LastPasswordSet;
    }
}

注意:您需要添加对System.DirectoryServices.AccountManagement的引用

[编辑:回应评论中的进一步问题]

测试密码是否是在一个月前设置的 - 类似这样:

if (lastPasswordSet < DateTime.Now.AddMonths(-1))
{
   // Password last set over a month ago.
}

要记住的一点是,一个月是一段不明确的时间长度——它的长度取决于你所处的月份(和年份)。根据你想要做的事情,它可能更适合拥有固定期限,例如 28 天。

【讨论】:

  • 如何将此属性与当前日期进行比较,看看它是否比今天早一个月
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-19
  • 1970-01-01
  • 1970-01-01
  • 2020-02-27
相关资源
最近更新 更多