最近一直在ldap开发项目中 对ldap方方面面都接触到很多 之前很多都是基本的操作,增删改查,配事物,连接池,这些只要会用spring的人应该都可以很轻松的弄出来,其实spring-ldap的提供了很好的说明。接下来 说下认证的问题,这个是我今天才弄好的。
可以看到官网的文档上有个相关的认证的方法 在第10章,但是有一个问题,如果你没有按照文档去配置事物的话 他是可以认证通过的,如果你按照文档去配了事物 再去调用验证发放他会报异常 说你找不到 ContextSource 这是因为在第6章的时候 它把跟服务器连接的id改为contextSourceTarget
但是在LDAP中contextSource这个 不只是一个id那么简单 因为在LDAP的世界里 他有一个接口也叫ontextSource 是用来验证使用的 所以你在不配置事物的时候是可以用的。
接下来上两段代码,事物是与jpa集合好的:
<bean id="contextSource" class="org.springframework.ldap.core.support.LdapContextSource"> <property name="url" value="ldap://127.0.0.1:389" /> <property name="userDn" value="cn=Directory Manager " /> <property name="password" value="******" /> </bean> <bean id="contextSourceTarget" class="org.springframework.ldap.transaction.compensating.manager.TransactionAwareContextSourceProxy"> <constructor-arg ref="contextSource" /> </bean> <bean id="ldapTemplateAuthention" class="org.springframework.ldap.core.LdapTemplate"> <constructor-arg ref="contextSource" /> </bean> <bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate"> <constructor-arg ref="contextSourceTarget" /> </bean> <bean id="transactionManager" class="com.smarcloud.control.util.ContextSourceAndJpaTransactionManager"> <property name="contextSource" ref="contextSourceTarget"/> <property name="entityManagerFactory" ref="entityManagerFactory"/><!-- 这个是jpa的 --> </bean> <tx:annotation-driven transaction-manager="transactionManager" />
改成这样就可以以确保你的认证方法是可用的了,同时还会有事物。
这里要结束下为什么要配2个ldapTemplate, 主要原因是在在于class="org.springframework.ldap.transaction.compensating.manager.TransactionAwareContextSourceProxy"spring的这里代理里面还不支持contextSource的验证(源码没做完很坑爹),所以单独写一个"ldapTemplateAuthention"用来单独做验证使用,"ldapTemplate"就做我们正常业务与事物。
下面是认证方法,官网拔下来的0.0:
public boolean authentication(String uid){ CollectingAuthenticationErrorCallback errorCallback = new CollectingAuthenticationErrorCallback(); String filter = "(&(objectclass=inetOrgPerson)(uid=" + uid + "))"; boolean result = ldapTemplateAuthention.authenticate("", filter.toString(), "123456", errorCallback); if (!result) { Exception error = errorCallback.getError(); // error is likely of type org.springframework.ldap.AuthenticationException error.printStackTrace(); } return result; }
OK,认证成功为true 不成功就是false 还带异常。
转载于:https://blog.51cto.com/jueshizhanhun/1272001