LDAP 认证
LDAP(轻量级目录访问协议)常被组织用作用户信息的中央存储库和认证服务。它也可以用来存储应用程序用户的角色信息。
LDAP 服务器的配置有多种不同的场景,因此 Spring Security 的 LDAP 提供程序是完全可配置的。它为身份验证和角色检索使用单独的策略接口,并提供了默认实现,这些默认实现可以配置以处理各种情况。
必需的依赖项
要开始使用,请将 spring-security-ldap
依赖项添加到您的项目中。当使用 Spring Boot 时,添加以下依赖项:
- Maven
- Gradle
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-ldap</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
</dependency>
depenendencies {
implementation "org.springframework.boot:spring-boot-starter-data-ldap"
implementation "org.springframework.security:spring-security-ldap"
}
先决条件
在尝试将LDAP与Spring Security一起使用之前,您应该对LDAP有所了解。以下链接提供了涉及的概念介绍以及使用免费的LDAP服务器OpenLDAP设置目录的指南:www.zytrax.com/books/ldap/。对从Java访问LDAP所使用的JNDI API有一些了解也是有用的。我们在LDAP提供程序中没有使用任何第三方LDAP库(Mozilla、JLDAP或其他),但大量使用了Spring LDAP,因此如果您打算添加自己的自定义内容,对该项目有一些了解可能会有所帮助。
在使用 LDAP 身份验证时,应确保正确配置 LDAP 连接池。如果您不熟悉如何操作,请参阅 Java LDAP 文档。
设置嵌入式 LDAP 服务器
你需要做的第一件事是确保你有一个LDAP服务器来指向你的配置。为了简单起见,通常最好从一个嵌入式LDAP服务器开始。Spring Security支持使用以下任一选项:
在以下示例中,我们将 users.ldif
作为类路径资源公开,以使用两个用户 user
和 admin
初始化嵌入式 LDAP 服务器,这两个用户的密码均为 password
:
dn: ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: groups
dn: ou=people,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: people
dn: uid=admin,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Rod Johnson
sn: Johnson
uid: admin
userPassword: password
dn: uid=user,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Dianne Emu
sn: Emu
uid: user
userPassword: password
dn: cn=user,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfNames
cn: user
member: uid=admin,ou=people,dc=springframework,dc=org
member: uid=user,ou=people,dc=springframework,dc=org
dn: cn=admin,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfNames
cn: admin
member: uid=admin,ou=people,dc=springframework,dc=org
嵌入式 UnboundID 服务器
如果你希望使用 UnboundID,请指定以下依赖项:
- Maven
- Gradle
<dependency>
<groupId>com.unboundid</groupId>
<artifactId>unboundid-ldapsdk</artifactId>
<version>6.0.11</version>
<scope>runtime</scope>
</dependency>
depenendencies {
runtimeOnly "com.unboundid:unboundid-ldapsdk:6.0.11"
}
然后,您可以使用 EmbeddedLdapServerContextSourceFactoryBean
配置嵌入式 LDAP 服务器。这将指示 Spring Security 启动一个内存中的 LDAP 服务器:
- Java
- Kotlin
@Bean
public EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() {
return EmbeddedLdapServerContextSourceFactoryBean.fromEmbeddedLdapServer();
}
@Bean
fun contextSourceFactoryBean(): EmbeddedLdapServerContextSourceFactoryBean {
return EmbeddedLdapServerContextSourceFactoryBean.fromEmbeddedLdapServer()
}
或者,你可以手动配置嵌入式 LDAP 服务器。如果你选择这种方法,你将负责管理嵌入式 LDAP 服务器的生命周期。
- Java
- XML
- Kotlin
@Bean
UnboundIdContainer ldapContainer() {
return new UnboundIdContainer("dc=springframework,dc=org",
"classpath:users.ldif");
}
<b:bean class="org.springframework.security.ldap.server.UnboundIdContainer"
c:defaultPartitionSuffix="dc=springframework,dc=org"
c:ldif="classpath:users.ldif"/>
@Bean
fun ldapContainer(): UnboundIdContainer {
return UnboundIdContainer("dc=springframework,dc=org","classpath:users.ldif")
}
嵌入式 ApacheDS 服务器
Spring Security 使用 ApacheDS 1.x,但该版本已不再维护。遗憾的是,ApacheDS 2.x 仅发布了里程碑版本,尚无稳定版。一旦有 ApacheDS 2.x 的稳定版发布,我们将考虑进行更新。
如果你希望使用 Apache DS,请指定以下依赖项:
- Maven
- Gradle
<dependency>
<groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-core</artifactId>
<version>1.5.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-server-jndi</artifactId>
<version>1.5.5</version>
<scope>runtime</scope>
</dependency>
depenendencies {
runtimeOnly "org.apache.directory.server:apacheds-core:1.5.5"
runtimeOnly "org.apache.directory.server:apacheds-server-jndi:1.5.5"
}
然后您可以配置嵌入式 LDAP 服务器:
- Java
- XML
- Kotlin
@Bean
ApacheDSContainer ldapContainer() {
return new ApacheDSContainer("dc=springframework,dc=org",
"classpath:users.ldif");
}
<b:bean class="org.springframework.security.ldap.server.ApacheDSContainer"
c:defaultPartitionSuffix="dc=springframework,dc=org"
c:ldif="classpath:users.ldif"/>
@Bean
fun ldapContainer(): ApacheDSContainer {
return ApacheDSContainer("dc=springframework,dc=org", "classpath:users.ldif")
}
LDAP ContextSource
一旦你有了一个LDAP服务器来指向你的配置,你需要配置Spring Security以指向应该用于认证用户的LDAP服务器。为此,创建一个LDAP ContextSource
(这相当于JDBC DataSource
)。如果你已经配置了一个EmbeddedLdapServerContextSourceFactoryBean
,Spring Security将创建一个指向嵌入式LDAP服务器的LDAP ContextSource
。
- Java
- Kotlin
@Bean
public EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() {
EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean =
EmbeddedLdapServerContextSourceFactoryBean.fromEmbeddedLdapServer();
contextSourceFactoryBean.setPort(0);
return contextSourceFactoryBean;
}
@Bean
fun contextSourceFactoryBean(): EmbeddedLdapServerContextSourceFactoryBean {
val contextSourceFactoryBean = EmbeddedLdapServerContextSourceFactoryBean.fromEmbeddedLdapServer()
contextSourceFactoryBean.setPort(0)
return contextSourceFactoryBean
}
或者,你可以显式地配置 LDAP ContextSource
以连接到提供的 LDAP 服务器:
- Java
- XML
- Kotlin
ContextSource contextSource(UnboundIdContainer container) {
return new DefaultSpringSecurityContextSource("ldap://localhost:53389/dc=springframework,dc=org");
}
<ldap-server
url="ldap://localhost:53389/dc=springframework,dc=org" />
fun contextSource(container: UnboundIdContainer): ContextSource {
return DefaultSpringSecurityContextSource("ldap://localhost:53389/dc=springframework,dc=org")
}
身份验证
Spring Security 的 LDAP 支持不使用 UserDetailsService,因为 LDAP 绑定认证不允许客户端读取密码,甚至不允许读取密码的哈希版本。这意味着没有方法可以读取密码并由 Spring Security 进行认证。
由于这个原因,LDAP 支持通过 LdapAuthenticator
接口实现。LdapAuthenticator
接口还负责检索任何必需的用户属性。这是因为属性上的权限可能依赖于所使用的认证类型。例如,如果以用户身份绑定,可能需要使用用户自己的权限来读取属性。
Spring Security 提供了两种 LdapAuthenticator
实现:
使用 Bind 身份验证
Bind 身份验证 是使用 LDAP 对用户进行身份验证的最常见机制。在 bind 身份验证中,用户的凭据(用户名和密码)被提交到 LDAP 服务器,由其进行身份验证。使用 bind 身份验证的优点是,用户的密钥(密码)不需要暴露给客户端,这有助于防止它们泄露。
以下示例展示了绑定认证配置:
- Java
- XML
- Kotlin
@Bean
AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSource) {
LdapBindAuthenticationManagerFactory factory = new LdapBindAuthenticationManagerFactory(contextSource);
factory.setUserDnPatterns("uid={0},ou=people");
return factory.createAuthenticationManager();
}
<ldap-authentication-provider
user-dn-pattern="uid={0},ou=people"/>
@Bean
fun authenticationManager(contextSource: BaseLdapPathContextSource): AuthenticationManager {
val factory = LdapBindAuthenticationManagerFactory(contextSource)
factory.setUserDnPatterns("uid={0},ou=people")
return factory.createAuthenticationManager()
}
前面的简单示例会通过在提供的模式中替换成用户的登录名来获取该用户的 DN,并尝试使用登录密码以该用户身份进行绑定。如果你的所有用户都存储在目录中的单个节点下,这样做是可以的。相反,如果你希望配置一个 LDAP 搜索过滤器来定位用户,你可以使用以下方法:
- Java
- XML
- Kotlin
@Bean
AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSource) {
LdapBindAuthenticationManagerFactory factory = new LdapBindAuthenticationManagerFactory(contextSource);
factory.setUserSearchFilter("(uid={0})");
factory.setUserSearchBase("ou=people");
return factory.createAuthenticationManager();
}
<ldap-authentication-provider
user-search-filter="(uid={0})"
user-search-base="ou=people"/>
@Bean
fun authenticationManager(contextSource: BaseLdapPathContextSource): AuthenticationManager {
val factory = LdapBindAuthenticationManagerFactory(contextSource)
factory.setUserSearchFilter("(uid={0})")
factory.setUserSearchBase("ou=people")
return factory.createAuthenticationManager()
}
如果与前面展示的 ContextSource
定义 一起使用,这将在 DN ou=people,dc=springframework,dc=org
下使用 (uid={0})
作为过滤器执行搜索。同样,用户的登录名将替换过滤器名称中的参数,因此它会搜索 uid
属性等于用户名的条目。如果未提供用户搜索基,则从根目录开始搜索。
使用密码认证
密码比较是指将用户提供的密码与存储库中存储的密码进行比较。这可以通过检索密码属性的值并在本地进行检查来完成,或者通过执行LDAP“比较”操作来完成,在这种操作中,提供的密码被传递给服务器进行比较,而真实的密码值永远不会被检索出来。当密码使用随机盐值正确哈希后,无法进行LDAP比较。
- Java
- XML
- Kotlin
@Bean
AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSource) {
LdapPasswordComparisonAuthenticationManagerFactory factory = new LdapPasswordComparisonAuthenticationManagerFactory(
contextSource, NoOpPasswordEncoder.getInstance());
factory.setUserDnPatterns("uid={0},ou=people");
return factory.createAuthenticationManager();
}
<ldap-authentication-provider
user-dn-pattern="uid={0},ou=people">
<password-compare />
</ldap-authentication-provider>
@Bean
fun authenticationManager(contextSource: BaseLdapPathContextSource?): AuthenticationManager? {
val factory = LdapPasswordComparisonAuthenticationManagerFactory(
contextSource, NoOpPasswordEncoder.getInstance()
)
factory.setUserDnPatterns("uid={0},ou=people")
return factory.createAuthenticationManager()
}
以下示例展示了一个带有某些自定义项的更高级配置:
- Java
- XML
- Kotlin
@Bean
AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSource) {
LdapPasswordComparisonAuthenticationManagerFactory factory = new LdapPasswordComparisonAuthenticationManagerFactory(
contextSource, new BCryptPasswordEncoder());
factory.setUserDnPatterns("uid={0},ou=people");
factory.setPasswordAttribute("pwd"); 1
return factory.createAuthenticationManager();
}
<ldap-authentication-provider
user-dn-pattern="uid={0},ou=people">
<password-compare password-attribute="pwd"> // <1>
<password-encoder ref="passwordEncoder" /> // <2>
</password-compare>
</ldap-authentication-provider>
<b:bean id="passwordEncoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
@Bean
fun authenticationManager(contextSource: BaseLdapPathContextSource): AuthenticationManager {
val factory = LdapPasswordComparisonAuthenticationManagerFactory(
contextSource, BCryptPasswordEncoder()
)
factory.setUserDnPatterns("uid={0},ou=people")
factory.setPasswordAttribute("pwd") 1
return factory.createAuthenticationManager()
}
将密码属性指定为
pwd
。
LdapAuthoritiesPopulator
Spring Security 的 LdapAuthoritiesPopulator
用于确定为用户返回哪些权限。以下示例展示了如何配置 LdapAuthoritiesPopulator
:
- Java
- XML
- Kotlin
@Bean
LdapAuthoritiesPopulator authorities(BaseLdapPathContextSource contextSource) {
String groupSearchBase = "";
DefaultLdapAuthoritiesPopulator authorities =
new DefaultLdapAuthoritiesPopulator(contextSource, groupSearchBase);
authorities.setGroupSearchFilter("member={0}");
return authorities;
}
@Bean
AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSource, LdapAuthoritiesPopulator authorities) {
LdapBindAuthenticationManagerFactory factory = new LdapBindAuthenticationManagerFactory(contextSource);
factory.setUserDnPatterns("uid={0},ou=people");
factory.setLdapAuthoritiesPopulator(authorities);
return factory.createAuthenticationManager();
}
<ldap-authentication-provider
user-dn-pattern="uid={0},ou=people"
group-search-filter="member={0}"/>
@Bean
fun authorities(contextSource: BaseLdapPathContextSource): LdapAuthoritiesPopulator {
val groupSearchBase = ""
val authorities = DefaultLdapAuthoritiesPopulator(contextSource, groupSearchBase)
authorities.setGroupSearchFilter("member={0}")
return authorities
}
@Bean
fun authenticationManager(
contextSource: BaseLdapPathContextSource,
authorities: LdapAuthoritiesPopulator): AuthenticationManager {
val factory = LdapBindAuthenticationManagerFactory(contextSource)
factory.setUserDnPatterns("uid={0},ou=people")
factory.setLdapAuthoritiesPopulator(authorities)
return factory.createAuthenticationManager()
}
Active Directory
Active Directory 支持其自己的非标准身份验证选项,并且通常的使用模式与标准的 LdapAuthenticationProvider
不太匹配。通常,身份验证是通过使用域用户名(形式为 user@domain
)而不是使用 LDAP 区分名称来执行的。为了简化这一过程,Spring Security 提供了一个针对典型的 Active Directory 设置定制的身份验证提供者。
配置 ActiveDirectoryLdapAuthenticationProvider
非常简单。您只需提供域名和一个提供服务器地址的 LDAP URL 即可。
也可以通过使用DNS查询来获取服务器的IP地址。目前尚不支持此功能,但希望在未来的版本中可以实现。
以下示例配置 Active Directory:
- Java
- XML
- Kotlin
@Bean
ActiveDirectoryLdapAuthenticationProvider authenticationProvider() {
return new ActiveDirectoryLdapAuthenticationProvider("example.com", "ldap://company.example.com/");
}
<bean id="authenticationProvider"
class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
<constructor-arg value="example.com" />
<constructor-arg value="ldap://company.example.com/" />
</bean>
@Bean
fun authenticationProvider(): ActiveDirectoryLdapAuthenticationProvider {
return ActiveDirectoryLdapAuthenticationProvider("example.com", "ldap://company.example.com/")
}