ba

Friday, July 16, 2010

การเขียน c#.net เพื่อติดต่อกับ LDAP

ในตัวอย่างนี้ผมทดสอบ ดึง username,password มาจาก Window Server ในส่วนของ OU นะครับซึ่งใน OU (Organization Unit ) นี้ผมได้เก็บชื่อ user ต่างๆมากมายรวมถึงเก็บ สิทธิ์ในการ login เข้าเข้าสู่ window serverผมได้สร้าง web form ขึ้นมา หน้านึง ที่มีหน้าตาดังรูป
จากนั้น ก็คลิกที่ปุ่ม Submit แล้วเขียนโค้ดดังนี้(ก่อนที่จะใช้งาน DirectoryEntry ให้ไป add reference library ที่ชื่อ System.DirectoryServices ก่อน จากนั้นก็เรียกใช้ using System.DirectoryServices;และในการติดต่อ ldap สิ่งแรกคือจะต้องรู้ LDAP Server ก่อนนะครับ )
ตัวอย่างโค้ด protected void Button1_Click(object sender, EventArgs e)
{
string username = txtUsername.Text;
string password = txtPassword.Text;
string path = "192.x.x.x"; //ip ของ window server ที่จะติดต่อ
DirectoryEntry direct_entry = new DirectoryEntry();
direct_entry.Path = path;
direct_entry.Username = username;
direct_entry.Password = password;
if (IsCheckUserExist(username)) //ถ้ามี user อยู่ในระบบจริงก็ให้ไปที่หน้า hellomember.aspx
{
Response.Redirect("hellomember.aspx");
}
else
{
Response.Write("กรุณาใส่ username,password ให้ถูกต้อง");
}
}
public bool IsCheckUserExist(string username)
{
DirectoryEntry direct_entry = GetDirectoryEntry();
DirectorySearcher direct_search = new DirectorySearcher();
direct_search.SearchRoot = direct_entry;
direct_search.Filter = "(&(ObjectClass=user)(SAMAccountName=" + username + "))"; //ตรวจสอบเฉพาะ username ที่ใส่เข้ามาทาง textbox
SearchResultCollection result_col = direct_search.FindAll();
return result_col.Count > 0; //ถ้ามี username ชื่อนี้อยู่ในระบบ server จริงก็ให้ ส่งค่า true ไปที่ event ที่ชื่อ Button1_Click
}
public DirectoryEntry GetDirectoryEntry()
{ DirectoryEntry direct_entry = new DirectoryEntry("LDAP://192.x.x.x",txtUsername.Text,txtPassword.Text);//กำหนด LDAP Server , username,password
direct_entry.AuthenticationType = AuthenticationTypes.Secure;
return direct_entry;
}
นี้เป็นตัวอย่างโค้ดที่ผมเขียนขึ้นเพื่อติดต่อ LDAP ผมเขียนใน Website นะครับถ้าจะทำเป็น web service ก็เขียนคล้ายกับตัวอย่างนี้ลองเอาไปประยุกต์ใช้ดูครับ
โดยสิ่งสำคัญหลักๆใน ตัวอย่างนี้คือ ให้ผู้ใช้ สามารถ login ผ่านหน้า web site ได้ โดยผู้ใช้งานจะต้องมี username,password อยู่ใน ส่วนของ OU ใน Window server ก่อน
แล้วพอกดปุ่ม Submit ทางโปรแกรมก็จะติดต่อ เพื่อตรวจสอบ username,password ผ่าน protocal : LDAP

No comments:

Post a Comment