LDAP 认证

LDAP(轻量级目录访问协议)常被组织用作用户信息的中央存储库和认证服务。它也可用于存储应用程序用户的角色信息。

当 Spring Security 配置为接受用户名/密码进行认证时,会使用 Spring Security 基于 LDAP 的认证。然而,尽管使用了用户名和密码进行认证,它并不使用 UserDetailsService,因为在绑定认证中,LDAP 服务器不返回密码,因此应用程序无法执行密码验证。

LDAP 服务器的配置方式有许多不同的场景,因此 Spring Security 的 LDAP 提供者是完全可配置的。它使用独立的策略接口进行认证和角色检索,并提供了默认实现,这些实现可以配置以处理各种情况。

所需的依赖项

要开始使用,请将 spring-security-ldap 依赖项添加到您的项目。使用 Spring Boot 时,请添加以下依赖项

Spring Security LDAP 依赖项
  • 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"
}

先决条件

在使用 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 文件暴露为类路径资源,用于初始化嵌入式 LDAP 服务器,其中包含两个用户:useradmin,它们的密码均为 password

users.ldif
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,请指定以下依赖项

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 服务器

嵌入式 LDAP 服务器配置
  • Java

  • Kotlin

@Bean
public EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() {
	return EmbeddedLdapServerContextSourceFactoryBean.fromEmbeddedLdapServer();
}
@Bean
fun contextSourceFactoryBean(): EmbeddedLdapServerContextSourceFactoryBean {
    return EmbeddedLdapServerContextSourceFactoryBean.fromEmbeddedLdapServer()
}

或者,您可以手动配置嵌入式 LDAP 服务器。如果您选择这种方法,您将负责管理嵌入式 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,请指定以下依赖项

ApacheDS 依赖项
  • 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 服务器

嵌入式 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

带有嵌入式 LDAP 服务器的 LDAP Context Source
  • 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 服务器

LDAP Context Source
  • 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 实现:

使用绑定认证

绑定认证是使用 LDAP 认证用户最常见的机制。在绑定认证中,用户的凭据(用户名和密码)被提交给 LDAP 服务器进行认证。使用绑定认证的优势在于用户的机密信息(密码)无需暴露给客户端,这有助于保护它们不被泄露。

以下示例展示了绑定认证配置

绑定认证
  • 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 定义一起使用,这将通过使用 (uid={0}) 作为过滤器,在 DN ou=people,dc=springframework,dc=org 下执行搜索。同样,用户登录名被替换为过滤器名称中的参数,因此它会搜索 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()
}
1 将密码属性指定为 pwd

LdapAuthoritiesPopulator

Spring Security 的 LdapAuthoritiesPopulator 用于确定为用户返回哪些权限。以下示例展示了如何配置 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 判别名(distinguished name)来执行的。为了简化此过程,Spring Security 提供了一个专门为典型 Active Directory 设置定制的认证提供者。

配置 ActiveDirectoryLdapAuthenticationProvider 非常简单。您只需提供域名和提供服务器地址的 LDAP URL。

也可以通过 DNS 查找来获取服务器的 IP 地址。目前尚不支持此功能,但希望未来的版本会支持。

以下示例配置 Active Directory

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/")
}