最近要做 OpenLdap 的 Authorization , 但是一直 try 不成功,直到看到以下的回覆,真的是幫助很大
http://www.cnblogs.com/wangyt223/archive/2012/10/09/2716077.html
(转)DirectoryServices访问OpenLdap的若干问题
DirectoryServices访问OpenLdap的若干问题 (入选推荐日志,加10币)
昨天晚上快2点才睡,终于把使用DirectoryServices访问OpenLdap的所有问题都解决了,这方面的资料好像国内的不多,遇到很多问题都是自己摸索,或者在国外的论坛上看到的。
1.DirectoryEntry的AuthenticationTypes必须设置成ServerBind
2.ldap直接认证,可以使用DirectoryEntry.NativeObject,只要不返回错误,就可以认为认证成功
3.搜索可以使用DirectorySearcher,调用 mySearchResult.GetDirectoryEntry可以对搜索项进行修改
4.Attribute Types 为Octet String 的必须string和asc byte数组类型之间转换(该类型一般用在password上)
5.新加用户使用DirectoryEntry.Children.Add的方法,该方面有两个参数,一个是dn,另一个为加入的Schema 的objectclass(注意千万不要忘记了所有在Schema中定义的必填项,否则会返回LDAP_NAMING_VIOLATION的错误)
6.当然,任何修改都需要.CommitChanges()
另外还有个遗留的小问题,Adsi Edit无法访问 OpenLdap,不知道是不是设置有问题
把 code 放上來,以供日後參考
public static string ValidateUser(string ComputerName, string UserName, string Password) { string strPath; if (ComputerName.IndexOf('.') != -1) { strPath = string.Format("LDAP://{0}:389/DC=alchip,DC=com",ComputerName);
UserName = string.Format("uid={0},ou=Users,DC=alchip,DC=com",UserName); } else { strPath = string.Format(@"WinNT://{0}/{1}, user", ComputerName, UserName); } DirectoryEntry entry = new DirectoryEntry(strPath, UserName, Password,AuthenticationTypes.ServerBind); try { //string objectSid = // (new SecurityIdentifier((byte[])entry.Properties["objectSid"].Value, 0).Value); //return objectSid; if (entry.NativeObject != null) return "true"; else return null; } catch// (DirectoryServicesCOMException) { return null; } finally { entry.Dispose(); } }