跳到主要內容

發表文章

目前顯示的是有「JNDI」標籤的文章

JNDI API相關文章

這裡主要記載我在安裝測試機器時,所做的API存取嘗試。 Search Base Hashtable < String , Object > env = new Hashtable < String , Object > ( ) ; env. put ( Context . INITIAL_CONTEXT_FACTORY , "com.sun.jndi.ldap.LdapCtxFactory" ) ; env. put ( Context . PROVIDER_URL , "ldap://192.168.1.13:389/dc=testldap,dc=org" ) ; env. put ( Context . SECURITY_AUTHENTICATION , "simple" ) ; env. put ( Context . SECURITY_PRINCIPAL , "cn=admin,dc=testldap,dc=org" ) ; env. put ( Context . SECURITY_CREDENTIALS , "123456" ) ;   DirContext ctx = null ; try { ctx = new InitialDirContext ( env ) ;   NamingEnumeration < SearchResult > srs = ctx. search ( "" , null ) ; while ( srs. hasMore ( ) ) { SearchResult sr = srs. next ( ) ; System . out . println ( sr ) ; } } catch ( NamingException e ) { throw new RuntimeException ( e ) ; } finally { closeDirContext ( ctx ) ; } Output: cn=admin: null:null:{userpassw...

JNDI API - LdapName

Introduction 做LDAP認證系統整合時,一定會遇到處理登入帳號的問題。有的系統會讓使用者定義user filter,僅僅輸入uid或mail即可登入;有的系統則是要求完整的DN。僅輸入uid或mail讓使用者不需要記住完整的DN,但有可能在不同OU下,會有重複的uid。我們系統是兩種方式都允許的,也因此我們必須先針對使用者輸入,去確認為DN或者user filter方式。 How to? 判斷使用者輸入是否為DN,可以透過JNDI的LdapName。其實spring有提供DistinguishedName類別,但在2.0版本已被列為@deprecated,並推薦使用javax.naming.ldap.LdapName。 Is a valid DN? 在LdapName建構時,如果不是一個合法的DN格式,就會丟出InvalidNameException;因此我們可以透過這個方式判斷是否為合法格式的DN: @Test public void testValidDN ( ) { try { new LdapName ( "uid = tonylin,dc=tonylin,dc=org" ) ; } catch ( InvalidNameException e ) { Assert . fail ( "Should pass" ) ; } } @Test public void testinValidDN ( ) { try { new LdapName ( "tonylin@tonylin.org" ) ; Assert . fail ( "Should throw exception" ) ; } catch ( InvalidNameException e ) { } } Does DN contains DC? 我們不會要求使用者一定要輸入完整的DN。但如果使用者輸入完整的DN,在做搜尋時,我們就必須將DC部分給取代掉。因此,我們可以透過LdapName的startsWith去判斷DN是否包含DC,又可以不需要去管等號前後是否有空白的問題: @Test public ...