使用 C# 对用户进行 LDAP 身份验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11561689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:19:53  来源:igfitidea点击:

Using C# to authenticate user against LDAP

c#authenticationldap

提问by sunny days

I'm using DirectorySearcher to search for a user entry in LDAP server.

我正在使用 DirectorySearcher 在 LDAP 服务器中搜索用户条目。

DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://myserver/OU=People,O=mycompany";
de.AuthenticationType = AuthenticationTypes.None;

DirectorySearcher deSearch = new DirectorySearcher();

deSearch.SearchRoot = de;
deSearch.Filter = "(uid=" + model.UserName + ")";

SearchResult result = deSearch.FindOne();

I'm able to get th intended output in result variable.
However If I try to authenticate the same user by providing password in directory entry, I always get following error.

我能够在结果变量中获得预期的输出。
但是,如果我尝试通过在目录条目中提供密码来验证同一用户,我总是会收到以下错误。

"The user name or password is incorrect."

“用户名或密码不正确。”

DirectoryEntry entry = new DirectoryEntry("LDAP://myserver/OU=People,O=mycompany", username, password);
DirectorySearcher search = new DirectorySearcher(
    entry,
    "(uid=" + username + ")",
    new string[] { "uid" }
);

search.SearchScope = System.DirectoryServices.SearchScope.Subtree;
SearchResult found = search.FindOne();   ->>>>>this is where I get wrong credential error.

The username and password are for the user I want to authenticate.

用户名和密码用于我要验证的用户。

Can anyone tell me what I'm doing wrong here or how to debug this.

谁能告诉我我在这里做错了什么或如何调试。

采纳答案by loopedcode

This username, password within this line:

此行中的此用户名和密码:

DirectoryEntry("LDAP://myserver/OU=People,O=mycompany", username, password);

should be for an account that has permission for directory lookup. It could be a service account or testing purpose try with your own. This shouldn't be the user/pass of someone who you are trying to authenticate.

应该用于具有目录查找权限的帐户。它可能是服务帐户或测试目的,请尝试使用您自己的帐户。这不应该是您尝试进行身份验证的人的用户/通行证。

If you want to authenticate, you can use following steps using PrincipalContext:

如果要进行身份验证,可以使用 PrincipalContext 使用以下步骤:

using(var context = new PrincipalContext(ContextType.Domain, "mydomain", "mydomain\serviceAcct", "serviceAcctPass")) {
 //Username and password for authentication.
 return context.ValidateCredentials(username, password); 
}

"serviceAcct" = an account within domain users that has permission for directory lookup. "serviceAcctPass" = password for that service account. As I said, for testing you can try with your own user/pass context.

“serviceAcct” = 域用户中具有目录查找权限的帐户。“serviceAcctPass” = 该服务帐户的密码。正如我所说,为了测试,您可以尝试使用自己的用户/密码上下文。

Also, make sure supplied username has either "domain\username" or "username@domain" formatting.

此外,请确保提供的用户名具有“域\用户名”或“用户名@域”格式。

回答by Sandeep Kumar Singh

Here we are getting the active directory user details and we can use DomainName and UserRole from web.config file

在这里,我们正在获取活动目录用户详细信息,我们可以使用 web.config 文件中的 DomainName 和 UserRole

bool isAdmin = false;
        RegisterInput model = new RegisterInput();
        NewUserInput usr = new NewUserInput();
        SearchResultCollection results;
        string mobileNumber = string.Empty;
        using (DirectoryEntry domainEntry = new DirectoryEntry("LDAP://" + AppSettings.DomainName))
        {
            using (DirectorySearcher searcher = new DirectorySearcher(domainEntry, "userPrincipalName=" + userName + "@" + AppSettings.DomainName) { Filter = string.Format("(&(objectClass=user)(samaccountname={0}))", userName) })
            {
               results = searcher.FindAll();

                if (results.Count > 0)
                {
                    usr.FirstName = results[0].GetDirectoryEntry().Properties["givenName"].Value.ToString();
                    usr.LastName = results[0].GetDirectoryEntry().Properties["sn"].Value?.ToString();
                    usr.EmailAddress = results[0].GetDirectoryEntry().Properties["mail"].Value?.ToString();
                    mobileNumber = results[0].GetDirectoryEntry().Properties["mobile"]?.Value?.ToString();
                    dynamic userRoleList = results[0].GetDirectoryEntry().Properties["memberOf"];

                    if (userRoleList != null)
                    {
                        foreach (var role in userRoleList)
                        {
                            string[] split = role.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                            bool result = split.Any(x => x.ToLowerInvariant() == AppSettings.UserRole.ToLowerInvariant());
                            if (result)
                            {
                                isAdmin = true;
                                break;
                            }
                        }
                    }
                }
            }
        }

        model.NewUser = usr;