You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DirectorySearcher无法查询域中锁定用户的问题求助

解决思路

1. 调整LDAP过滤器,精准定位锁定用户

AD中用户锁定状态由lockoutTime属性标识,当该属性值大于0时表示用户处于锁定状态。你原有的过滤器仅按SAMAccountName查询,未关联锁定状态,可修改过滤器同时筛选账号和锁定状态:

string ls_userfilter = $"(&(SAMAccountName={myconfig.UserID})(lockoutTime>=1))";

如果需要查询指定账号并获取其锁定状态(不管是否锁定),保留原过滤器即可,但必须加载lockoutTime属性用于后续判断。

2. 明确指定要加载的属性

DirectorySearcher默认仅返回部分核心属性,需手动添加lockoutTime到属性加载列表,否则无法获取锁定状态信息:

searcher.PropertiesToLoad.Add("lockoutTime");
searcher.PropertiesToLoad.Add("SAMAccountName"); // 按需添加其他需要的属性

3. 验证绑定账号的权限

你当前使用null, null绑定目录,即采用当前进程上下文的身份认证。如果该身份没有读取用户lockoutTime属性的权限,会导致无法获取锁定用户信息。可尝试使用具备域用户读取权限的账号进行绑定:

var ld_directory = new DirectoryEntry(myconfig.LDAPPath, "DOMAIN\\AuthorizedUser", "UserPassword", 
    AuthenticationTypes.SecureSocketsLayer | AuthenticationTypes.Secure);

4. 完善结果解析逻辑

获取搜索结果后,通过解析lockoutTime属性值判断用户是否锁定:

foreach (SearchResult result in user)
{
    if (result.Properties.Contains("lockoutTime"))
    {
        long lockoutTime = (long)result.Properties["lockoutTime"][0];
        bool isLocked = lockoutTime > 0;
        // 此处添加你的业务处理逻辑
    }
}

完整修改示例代码

string ls_userfilter = $"(&(SAMAccountName={myconfig.UserID})(lockoutTime>=1))";

var ld_directory = new DirectoryEntry(myconfig.LDAPPath, "DOMAIN\\AuthorizedUser", "UserPassword", 
    AuthenticationTypes.SecureSocketsLayer | AuthenticationTypes.Secure);

SearchResultCollection userResults = null;

try
{
    var searcher = new DirectorySearcher(ld_directory);
    searcher.Filter = ls_userfilter;
    searcher.SearchScope = SearchScope.Subtree;
    // 指定需要加载的属性
    searcher.PropertiesToLoad.Add("SAMAccountName");
    searcher.PropertiesToLoad.Add("lockoutTime");
    
    userResults = searcher.FindAll();

    foreach (SearchResult result in userResults)
    {
        Console.WriteLine($"找到锁定用户: {result.Properties["SAMAccountName"][0]}");
        long lockoutTimeValue = (long)result.Properties["lockoutTime"][0];
        DateTime lockoutDateTime = DateTime.FromFileTimeUtc(lockoutTimeValue);
        Console.WriteLine("锁定时间: " + lockoutDateTime.ToString());
    }
}
catch (Exception ex)
{
    // 异常处理逻辑
    Console.WriteLine($"查询失败: {ex.Message}");
}
finally
{
    // 释放资源
    userResults?.Dispose();
    ld_directory.Dispose();
}

额外注意事项

  • 确认LDAP路径格式正确:需为LDAPS://yourdomain.com/DC=yourdomain,DC=com,确保服务器开启636端口的LDAPS服务,且客户端信任服务器SSL证书。
  • lockoutTime为AD文件时间格式,可通过DateTime.FromFileTimeUtc()转换为可读时间。

内容的提问来源于stack exchange,提问作者Storn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 02:32:23