2008年8月24日 星期日

.Net LDAP ADsPath Programming

[Original published date: 6/7/2007 8:31:17 PM]

在 DotNet 平台撰寫 AD 相關應用程式,最常使用到的莫過於 DirectoryEntry 物件。透過該類別的建構子,傳入欲取得之 LDAP 節點的 LDAP 路徑、具有 Query 權限的帳號名稱和密碼,便可以輕易取得該節點,進而檢視其細部屬性:

DirectoryEntry de = new DirectoryEntry( [LDAP Path], [具有AD瀏覽權限的帳號名稱], [具有AD瀏覽權限的帳號密碼]);

其中的第一個 LDAP Path,我們可以使用 ADsPath 格式以達到 Query AD 伺服器的目的,有關 ADsPath 的格式如次:

LDAP://HostName[:PortNumber][/DistinguishedName]

以下則是一些 ADsPath 的範例:

Bind to the root of the LDAP namespace
LDAP:

Bind to a specific server
LDAP://server01/

Bind to a specific server using the specified port number
LDAP://server01:390/

Bind to a specific object
LDAP://CN=Jeff/ Smith,CN=users,DC=fabrikam,DC=com

Bind to a specific object through a specific server
LDAP://server01/CN=Jeff Smith,CN=users,DC=fabrikam,DC=com

比較需要注意的地方是,ADsPath 是以 '/' 作為 hostnameDistinguishedName 的分界點,因此,程式開發是必須注意在後方的 DistinguishedName 當中是否有任意 LDAP 節點名稱包含了 '/' 字元(通常情況下,LDAP節點名稱是不可以包含任何特殊符號的,不過不遵守此一通則的情況比比皆是)。舉例來說,在下面這個 ADsPath, 因為後方的 DistinguishedName 路徑出現了 '/' 字元,故程式會將 [server01/CN=Jeff Smith,CN=users,DC=fabrikam] 這段路徑都當作 hostname 處理:

LDAP://server01/CN=Jeff Smith,CN=users,DC=fabrikam/taiwan,DC=com

因此,程式開發時必須特別留意 DistinguishedName 是否出現了不合法的字元,以上面的例子來說,我們必須將 '/' 加上脫逸符號成為 '\/',因此正確的 ADsPath 應該為:

LDAP://server01/CN=Jeff Smith,CN=users,DC=fabrikam\/taiwan,DC=com

參考資料:
http://msdn2.microsoft.com/en-us/library/aa706070.aspx
http://msdn2.microsoft.com/en-us/library/aa746384.aspx
http://msdn2.microsoft.com/en-us/library/aa772257.aspx
http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=/rzahy/rzahyunderdn.htm

[re-post this article due to database crash.]

沒有留言: