c# - LDAP 密码到期天数

标签 c# active-directory ldap

我有一个使用 Active Directory 进行身份验证的 Web 应用程序。我想添加一个选项,在用户的密码即将到期时通知用户。 我设法做了一些事情,但我遇到的问题是过期天数为负数(daysLeft 参数),但我仍然可以登录。

string domainAndUsername = @"LDAP://ldapUrl";

DirectoryEntry root = new DirectoryEntry(ldapServer, userID, userPwd, AuthenticationTypes.Secure);
DirectorySearcher mySearcher = new DirectorySearcher(root);
SearchResultCollection results;

string filter = "maxPwdAge=*";
mySearcher.Filter = filter;

results = mySearcher.FindAll();

long maxDays = 0;
if (results.Count >= 1)
{
    Int64 maxPwdAge = (Int64)results[0].Properties["maxPwdAge"][0];
    maxDays = maxPwdAge / -864000000000;
}

mySearcher = new DirectorySearcher(root);
mySearcher.Filter = "(&(objectCategory=user)(samaccountname=" + userID + "))";

results = mySearcher.FindAll();
long daysLeft = 0;
if (results.Count >= 1)
{
    var lastChanged = results[0].Properties["pwdLastSet"][0];
    daysLeft = maxDays - DateTime.Today.Subtract(
        DateTime.FromFileTime((long)lastChanged)).Days;
}

由于如果用户的帐户已过期则用户无法登录,我猜我的错误是计算帐户到期前的剩余天数...但我似乎无法找到它的位置。

最佳答案

此代码段正常工作,我还有三天时间更改我的密码,包括今天:

    public static void Main(string[] args)
    {
        const ulong dataFromAD = 0xFFFFE86D079B8000;
        var ticks = -unchecked((long)dataFromAD);
        var maxPwdAge = TimeSpan.FromTicks(ticks);

        var pwdLastSet = new DateTime(2015,12,16,9,19,13);

        var pwdDeadline = (pwdLastSet + maxPwdAge).Date;

        Console.WriteLine(pwdDeadline);

        Console.WriteLine(pwdDeadline - DateTime.Today);

        Console.ReadKey(true);
    }

我还验证了 TimeSpan.FromTicks(-(long)results[0].Properties["maxPwdAge"][0])DateTime.FromFileTime((long)results[ 0].Properties["pwdLastSet"][0]) 是从我们的 AD 中正确提取值的表达式。

关于c# - LDAP 密码到期天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34741136/

相关文章:

c# - 如何将枚举转换为整数

c# - 在特定 OU Active Directory 中搜索用户

delphi - 查询 Active Directory (AD),但不链接 "ActiveDs_TLB.pas"

tomcat - 通过LDAP SSL的Active Directory-开发环境与Tomcat-Grails Web应用

active-directory - 检查用户是否存在于 Active Directory 中

c# - 为什么数组项分配会降低 C# 程序的性能?

c# - Linq 按属性排序,然后按原始顺序

database - 通过 WCF 公开 DTO 时的不同类型的 Id

c# - 当 "User must change password on next log on"时,LDAP 验证失败。有什么解决办法吗?

c# - 在没有 typeNameHandling 的情况下将 Json 对象反序列化为多态 C# 对象