javascript
LDAP用户验证(Spring-LDAP)
LDAP-Lightweight Directory Access Protocol。LDAP服務器可以是任何一個開源或商用的LDAP目錄服務器,而客戶端都可以使用同樣的協議、客戶端連接軟件包和查詢命令與LDAP服務器進行交互。
LDAP目錄是樹形結構,目錄有條目組成。條目是具有區別名DN(Distinguished Name)的屬性(Attribute)集合,條目相當于表,DN相當于關系數據庫表中的關鍵字(Primary Key),屬性由類型(Type)和多個值(Values)組成。
DN-Distinguished?Name,區別名,具有唯一性;DC-District,所屬區域;OU-Organization Unit,所屬組織;CN/UID-Common Name/Unique ID 名字。
如下圖,uid-tsyroid的DN就是cn=tsyroid,ou=people,dc=syroidmanor,dc=com
本文使用Spring-LDAP進行用戶驗證,下載了1.3.1版本
applicationContex.xml配置文件
?
<bean id="contextSource" class="org.springframework.ldap.core.support.LdapContextSource"> <property name="url" value="ldap://192.168.0.22:389" /> <property name="base" value="dc=ygsoft,dc=com" /> <property name="userDn" value="whuqin@yahoo.com" /> <property name="password" value="1234.abcd" /><property name="referral" value="follow"></property></bean><bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate"> <constructor-arg ref="contextSource" /></bean> <bean id="userDao" class="cn.com.ldap.UserDaoLdapImpl"><property name="ldapTemplate"><ref bean="ldapTemplate"/></property></bean>?
userDn是用戶區別名,格式應該為cn=xxx,ou=xxx,dc=xxx。而本文是由于公司LDAP服務器設置,使用用戶的userPrincipalName進行唯一標示。注意referral要設置為follow,否則會出現異常“Unprocessed Continuation Reference(s);”,設置為follow的意思好像是自動接下處理。。。。
UserDaoLdapImpl關鍵代碼
private LdapTemplate ldapTemplate; private ContextSource contextSource;public void setLdapTemplate(LdapTemplate ldapTemplate) { this.ldapTemplate = ldapTemplate; } public void setContextSource(ContextSource contextSource) {this.contextSource = contextSource;}public boolean authenticate(String userName, String password) {AndFilter filter = new AndFilter();filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("userPrincipalName", userName));// Actual filter will differ depending on LDAP Server and schemaList<String> results = ldapTemplate.search("", filter.toString(),new DnContextMapper());if (results.size() != 1) return false;DirContext ctx = null;try {ctx = contextSource.getContext(results.get(0), password);return true;} catch (Exception e) {return false;} finally {LdapUtils.closeContext(ctx);}}private final static class DnContextMapper extendsAbstractParameterizedContextMapper<String> {@Overrideprotected String doMapFromContext(DirContextOperations ctx) {return ctx.getNameInNamespace();}}
這樣不管什么情況,都不會在控制臺出現異常提示了。
?
轉載于:https://www.cnblogs.com/whuqin/archive/2012/04/11/4982048.html
總結
以上是生活随笔為你收集整理的LDAP用户验证(Spring-LDAP)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为应用“瘦身”!给 Android 应用
- 下一篇: 11.Java面向对象(二)