C# LDAP认证登录

时间:2023-03-08 18:40:20
C# LDAP认证登录

LDAP是轻量目录访问协议,英文全称是Lightweight Directory Access Protocol,一般都简称为LDAP。它是基于X.500标准的,但是简单多了并且可以根据需要定制。与X.500不同,LDAP支持TCP/IP,这对访问Internet是必须的。LDAP的核心规范在RFC中都有定义,所有与LDAP相关的RFC都可以在LDAPman RFC网页中找到。

bool checkResult = false;
try
{
string username = Request.Params.Get("username");
string userpwd = Request.Params.Get("userpwd");
string strLADPath = "LDAP://OU=事业部,DC=HOLD,DC=Company,DC=COM"; DirectoryEntry objEntry = new DirectoryEntry(strLADPath);
objEntry.AuthenticationType = AuthenticationTypes.None; DirectorySearcher deSearch = new DirectorySearcher(objEntry);
//过滤名称是否存在
deSearch.Filter = "(&(objectClass=user)(sAMAccountName=" + username + "))";
deSearch.SearchScope = SearchScope.Subtree;
//find the first instance
SearchResult results = deSearch.FindOne();
//check username & userpwd
if (null != results)
{
DirectoryEntry objUserEntry = new DirectoryEntry(results.Path, username, userpwd);
if (null != objUserEntry && null != objUserEntry.Properties
&& objUserEntry.Properties.Contains("cn"))
{
checkResult = true;
}
} Response.Write("认证结果:" + checkResult.ToString());
}
catch (System.Exception ex)
{
Response.Write("认证异常"+ex.StackTrace);
Response.Write("认证结果:" + checkResult.ToString());
}