使用 Spring Security 保护 Web 应用的安全(7)
 
- UID
- 1066743
|

使用 Spring Security 保护 Web 应用的安全(7)
使用 LDAP很多公司都使用 LDAP 服务器来保存员工的相关信息。内部的 IT 系统都需要与 LDAP 服务器做集成来进行用户认证与访问授权。Spring Security 提供了对 LDAP 协议的支持,只需要简单的配置就可以让 Web 应用使用 LDAP 来进行认证。第二个示例应用使用 OpenDS LDAP 服务器并添加了一些测试用户。中给出了配置文件的示例,完整的代码见 。
清单 10. 集成 LDAP 服务器的配置文件1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| <bean id="contextSource"
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>
|
如 所示,配置中的核心部分是类 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 进行集成。 |
|
|
|
|
|