LdapName

做LDAP認證系統整合時,一定會遇到處理登入帳號的問題。有的系統會讓使用者定義user filter,僅僅輸入uid或mail即可登入;有的系統則是要求完整的DN。僅輸入uid或mail讓使用者不需要記住完整的DN,但有可能在不同OU下,會有重複的uid。我們系統是兩種方式都允許的,也因此我們必須先針對使用者輸入,去確認為DN或者user filter方式。

判斷使用者輸入是否為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 void testLdapName(){
	try {
		LdapName dn = new LdapName("uid = tonylin,dc=tonylin,dc=org");
		Assert.assertTrue(dn.startsWith(new LdapName("dc =tonylin,dc=org")));
		Assert.assertFalse(dn.startsWith(new LdapName("dc =tonylin,dc=com")));
	} catch (InvalidNameException e) {
		Assert.fail();
	}
}

Remove DC

LdapName提供remove,讓你可以針對index去移除DN中的項目:

@Test
public void removeDC(){
	try {
		LdapName dn = new LdapName("uid = tonylin,dc=tonylin,dc=org");
		dn.remove(0);
		Assert.assertTrue(dn.equals(new LdapName("uid=tonylin,dc=tonylin")));
		dn.remove(0);
		Assert.assertTrue(dn.equals(new LdapName("uid=tonylin")));
	} catch (InvalidNameException e) {
		Assert.fail();
	}
}
另外一個方式是直接取得Suffix。你可以根據DC的大小去決定Suffix的位置:
@Test
public void getSuffix(){
	try {
		LdapName dn = new LdapName("uid = tonylin,dc=tonylin,dc=org");
		Assert.assertTrue(dn.getSuffix(2)
				.equals(new LdapName("uid=tonylin")));
	} catch (InvalidNameException e) {
		Assert.fail();
	}
}