如何在C#LDAP中验证用户身份

时间:2017-09-21 13:59:50

标签: 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());
}

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

  

评论:根据管理员的说法,我已被分配到AD中的小组。但是我怎样才能确保我可以访问它?

好像是Active Directory。如果是这样,您可以使用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