清单 10. 集成 LDAP 服务器的配置文件
class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
<constructor-arg value="ldap://localhost:389" />
</bean>
<bean id="ldapAuthProvider"
class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider">
<constructor-arg>
<bean class="org.springframework.security.ldap.authentication.BindAuthenticator">
<constructor-arg ref="contextSource" />
<property name="userSearch">
<bean id="userSearch"
class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
<constructor-arg index="0" value="ou=People,dc=mycompany,dc=com" />
<constructor-arg index="1"
value="(&(uid={0})(objectclass=person))" />
<constructor-arg index="2" ref="contextSource" />
</bean>
</property>
</bean>
</constructor-arg>
<constructor-arg>
<bean class="mycompany.CompanyAuthoritiesPopulator"></bean>
</constructor-arg>
</bean>
<sec:authentication-manager>
<sec:authentication-provider ref="ldapAuthProvider" />
</sec:authentication-manager>
如 代码清单 10所示,配置中的核心部分是类 org.springframework.security.ldap.authentication.LdapAuthenticationProvider,它用来与 LDAP 服务器进行认证以及获取用户的权限信息。一般来说,与 LDAP 服务器进行认证的方式有两种。一种是使用用户提供的用户名和密码直接绑定到 LDAP 服务器;另外一种是比较用户提供的密码与 LDAP 服务器上保存的密码是否一致。前者通过类 org.springframework.security.ldap.authentication.BindAuthenticator来实现,而后者通过类 org.springframework.security. ldap.authentication.PasswordComparisonAuthenticator来实现。第二个示例应用中使用的是绑定的方式来进行认证。在进行绑定的时候,需要在 LDAP 服务器上搜索当前的用户。搜索的时候需要指定基本的识别名(Distinguished Name)和过滤条件。在该应用中,用户登录时使用的是其唯一识别符(uid),如 user.0,而在 LDAP 服务器上对应的识别名是 uid=user.0,ou=People,dc=mycompany,dc=com。通过使用过滤条件 (&(uid={0})(objectclass=person))就可以根据 uid来搜索到用户并进行绑定。当认证成功之后,就需要获取到该用户对应的权限。一般是通过该用户在 LDAP 服务器上所在的分组来确定的。不过在示例应用中展示了如何提供自己的实现来为用户分配权限。类 mycompany.CompanyAuthoritiesPopulator实现了 org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator接口,并为所有的用户分配了单一的角色 ROLE_USER。
在介绍完与 LDAP 进行集成之后,下面介绍如何与 OAuth 进行集成。