c# - 如何在 C# LDAP 中对用户进行身份验证

标签 c# asp.net ldap

我是 LDAP 相关编码的新手,今天我被要求开发一个代码来检查 LDAP 的用户身份验证。

我在网上找到的教程很简单,但我们公司的目录很复杂,我不知道如何编写代码。这是 LDAP 的信息。我已更改公司名称以隐藏名称。

uri = ldaps://ABC.ad.XYZ.com:636
user_filter = memberOf=CN=TENXAIRFLOWPROD,OU=Security Groups,OU=Normal Users and Groups,OU=Account Management Services,OU=AD Master OU,DC=ABC,DC=ad,DC=XYZ,DC=com
user_name_attr = sAMAccountName
superuser_filter = memberOf=CN=TENXAIRFLOWPROD_ADM,OU=Security Groups,OU=Normal Users and Groups,OU=Account Management Services,OU=AD Master OU,DC=ABC,DC=ad,DC=XYZ,DC=com
bind_user = SCGLOBAL\twiki
bind_password_cmd = python /bns/tenx/airflow/ldap_password.py
basedn = DC=ABC,DC=ad,DC=XYZ,DC=com
search_scope = SUBTREE

这是我开发的代码,但它给了我错误:

string username = "myUserName";
string domain = "ldaps://ABC.ad.XYZ.com:636"; 
string pwd = "myPasword";              
try
{
    DirectoryEntry entry = new DirectoryEntry(domain, username, pwd);
    //Bind to the native AdsObject to force authentication.
    object obj = entry.NativeObject;
    lblError.Text=("Login Successful");

    //search some info of this user if any
    DirectorySearcher search = new DirectorySearcher(entry);
    search.Filter = "(SAMAccountName=" + username + ")";
    SearchResult result = search.FindOne();
}
catch (Exception ex)
{
    lblError.Text=("Login failed: " + ex.ToString());
}

有人可以帮忙吗?

最佳答案

Comment: According to the admin , I have been assigned to the group in AD. But how can I make sure I can access it?

它看起来像事件目录。如果是这样,您可以使用 PrincipalContext

public bool ValidateCredentials(string domain, string username, string password)
{
    using (var context = new PrincipalContext(ContextType.Domain, domain))
    {
        return context.ValidateCredentials(username, password);
    }
}

public bool IsUserInAdGroup(string domain, string username, string adGroupName)
{
    bool result = false;
    using (var context = new PrincipalContext(ContextType.Domain, domain))
    {
        var user = UserPrincipal.FindByIdentity(context, username);
        if (user != null)
        {
            var group = GroupPrincipal.FindByIdentity(context, adGroupName);
            if (group != null && user.IsMemberOf(group))
                result = true;
        }
    }
    return result;
}

请确保引用System.DirectoryServices.AccountManagement

关于c# - 如何在 C# LDAP 中对用户进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46345978/

相关文章:

c# - 等待的任务不异步运行

javascript - 在没有 ActiveX 的情况下使用 javascript 启动 word?

c# - AutoMapper:将元组映射到元组

css - TextAreaFor在asp net mvc中不显示默认CSS样式

c++ - LDAP SASL 绑定(bind) C++

c# - WPF 多边形 : Area and Centroid 的基本计算

c# - Azure辅助角色刚开始工作

c# - 在 .NET Entity Framework 中调用 SaveChanges 时出现 InvalidOperationException

.net - 如何根据 objectGUID 获取 AD 用户的 'memberof' 属性值?

jdbc - Apache 四郎 : Use ldap for user authentication and database for roles/permissions?