如何從公司的AD SERVER抓取帳號、密碼及AD資訊到自己寫的系統中做登入驗證?而且,是用ASP.NET C# 的WEB FORM寫法的範例或可下載的範例程式。
Web.config
<connectionStrings>
<add name="ADConnectionString" connectionString="LDAP://domain_controller_address/DC=domain_name,DC=com" />
</connectionStrings>
ADHelper
using System.DirectoryServices;
public class ADHelper
{
public static bool ValidateUser(string username, string password)
{
bool result = false;
string adConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ADConnectionString"].ConnectionString;
DirectoryEntry entry = new DirectoryEntry(adConnectionString, username, password);
try
{
// 嘗試在AD中取得使用者資訊
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult sr = search.FindOne();
if (sr != null)
{
result = true;
// 取得使用者資訊
string displayName = sr.Properties["cn"][0].ToString();
// 在此處新增其他使用者資訊
}
}
catch (Exception ex)
{
// 處理例外
}
finally
{
entry.Close();
}
return result;
}
}
ASP.NET Web Forms
protected void btnLogin_Click(object sender, EventArgs e)
{
string username = txtUsername.Text.Trim();
string password = txtPassword.Text.Trim();
bool isValidUser = ADHelper.ValidateUser(username, password);
if (isValidUser)
{
lblResult.Text = "登入成功!";
}
else
{
lblResult.Text = "無效的使用者名稱或密碼!";
}
}