目前多数公司都用windows域管理用户和电脑,
因此在内部应用中,使用LDAP进行用户验证,并返回LDAP的用户信息,如员工工号就十分有意义,
以下是一段关键代码,对LDAP账号密码验证后,返回员工号,完整的例子见附件
注意要引用以下namespace
using System.DirectoryServices;
private static string GetEmpIDFromLDAP(string UserName, string password)
{
//return true;
DirectoryEntry AD = new DirectoryEntry("LDAP://RootDSE");
String str = AD.Properties["defaultNamingContext"][0].ToString();
AD.Path = "LDAP://" + str;
AD.Username = UserName;
AD.Password = password;
AD.AuthenticationType = AuthenticationTypes.Secure;
try
{
DirectorySearcher searcher = new DirectorySearcher(AD);
searcher.Filter = String.Format("(&(objectClass=user)(samAccountName={0}))", UserName);
System.DirectoryServices.SearchResult result = searcher.FindOne();
if (result != null)
{
string empid = result.Properties["employeenumber"][0].ToString();
return empid;
}
else
{
return "";
}
}
catch (Exception err)
{
string a = err.Message;
}
return "";
}