ASP.NET C# AD驗證登入(使用LDAP群組cn,ou,dc寫法)
Login.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.DirectoryServices;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public static string ValidateUser(string ComputerName, string UserName, string Password)
{
if (ComputerName.IndexOf('.') != -1)
{
DirectoryEntry entry = new DirectoryEntry("LDAP://test.com.tw/cn=" + UserName + ",ou=user,ou=test,ou=test,ou=manger,dc=test,dc=com,dc=tw", UserName, Password);
try
{
string objectSid =
(new SecurityIdentifier((byte[])entry.Properties["objectSid"].Value, 0).Value);
return objectSid;
}
catch
{
return null;
}
finally
{
entry.Dispose();
}
}
else
{
DirectoryEntry entry = new DirectoryEntry("WinNT://" + ComputerName, UserName, Password);
try
{
string objectSid =
(new SecurityIdentifier((byte[])entry.Properties["objectSid"].Value, 0).Value);
return objectSid;
}
catch
{
return null;
}
finally
{
entry.Dispose();
}
}
}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string strComputerName = "test.com.tw";
string strUserName = ((System.Web.UI.WebControls.Login)sender).UserName;
string strPassword = ((System.Web.UI.WebControls.Login)sender).Password;
string strValidateUser = ValidateUser(strComputerName, strUserName, strPassword);
if (strValidateUser != null)
{
e.Authenticated = true;
}
else
{
e.Authenticated = false;
}
}
}
LDAP的寫法若不正確將導致無法登入到AD,因此提供詳細寫法~
參考或是複製語法時,別忘了留個言喔 ^ ^ ~