LDAP Authentication

LDAP(轻型目录访问协议)经常被组织用作用户信息的中心存储库以及身份验证服务。它还可以用于存储应用程序用户的角色信息。

LDAP (Lightweight Directory Access Protocol) is often used by organizations as a central repository for user information and as an authentication service. It can also be used to store the role information for application users.

当 Spring Security 配置为 accept a username/password进行身份验证时,会使用 Spring Security 基于 LDAP 的身份验证。但是,尽管在身份验证中使用用户名和密码,但却没有使用 UserDetailsService,因为在 bind authentication中,LDAP 服务器不会返回密码,因此应用程序无法执行该密码的验证。

Spring Security’s LDAP-based authentication is used by Spring Security when it is configured to accept a username/password for authentication. However, despite using a username and password for authentication, it does not use UserDetailsService, because, in servlet-authentication-ldap-bind, the LDAP server does not return the password, so the application cannot perform validation of the password.

不同的 LDAP 服务器可以配置成很多不同的场景,因此 Spring Security 的 LDAP 提供程序是完全可配置的。它为身份验证和角色检索使用单独的策略接口,并提供可以配置为处理各种情况的默认实现。

There are many different scenarios for how an LDAP server can be configured, so Spring Security’s LDAP provider is fully configurable. It uses separate strategy interfaces for authentication and role retrieval and provides default implementations, which can be configured to handle a wide range of situations.

Prerequisites

在尝试将 LDAP 与 Spring Security 结合使用之前,您应该熟悉 LDAP。以下链接提供了对所涉及的概念的良好介绍,以及使用免费的 LDAP 服务器 OpenLDAP 设置目录的指南:[role="bare"][role="bare"]https://www.zytrax.com/books/ldap/. 熟悉用于从 Java 访问 LDAP 的 JNDI API 也可能会很有用。我们在 LDAP 提供程序中不使用任何第三方 LDAP 库(Mozilla、JLDAP 或其他库),但会广泛使用 Spring LDAP,因此如果您计划添加自己的自定义项,那么熟悉该项目可能会很有用。

You should be familiar with LDAP before trying to use it with Spring Security. The following link provides a good introduction to the concepts involved and a guide to setting up a directory using the free LDAP server, OpenLDAP: [role="bare"]https://www.zytrax.com/books/ldap/. Some familiarity with the JNDI APIs used to access LDAP from Java can also be useful. We do not use any third-party LDAP libraries (Mozilla, JLDAP, or others) in the LDAP provider, but extensive use is made of Spring LDAP, so some familiarity with that project may be useful if you plan on adding your own customizations.

在使用 LDAP 认证时,您应该确保正确配置 LDAP 连接池。如果您不熟悉如何执行此操作,请参阅 Java LDAP documentation

When using LDAP authentication, you should ensure that you properly configure LDAP connection pooling. If you are unfamiliar with how to do so, see the Java LDAP documentation.

Setting up an Embedded LDAP Server

首先要做的是确保拥有一个 LDAP 服务器来指向你的配置。为了简单起见,通常最好从一个嵌入式 LDAP 服务器开始。Spring Security 支持使用下列服务器:

The first thing you need to do is to ensure that you have an LDAP Server to which to point your configuration. For simplicity, it is often best to start with an embedded LDAP Server. Spring Security supports using either:

在以下示例中,我们将 users.ldif 公开为类路径资源,以便使用两个密码均为 passworduseradmin 初始化嵌入式 LDAP 服务器:

In the following samples, we expose users.ldif as a classpath resource to initialize the embedded LDAP server with two users, user and admin, both of which have a password of 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
uniqueMember: uid=admin,ou=people,dc=springframework,dc=org
uniqueMember: uid=user,ou=people,dc=springframework,dc=org

dn: cn=admin,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfNames
cn: admin
uniqueMember: uid=admin,ou=people,dc=springframework,dc=org

Embedded UnboundID Server

如果您希望使用 UnboundID,请指定以下依赖项:

If you wish to use UnboundID, specify the following dependencies:

UnboundID Dependencies
  • Maven

  • Gradle

<dependency>
	<groupId>com.unboundid</groupId>
	<artifactId>unboundid-ldapsdk</artifactId>
	<version>{unboundid-ldapsdk-version}</version>
	<scope>runtime</scope>
</dependency>
depenendencies {
	runtimeOnly "com.unboundid:unboundid-ldapsdk:{unboundid-ldapsdk-version}"
}

然后,您可以使用 EmbeddedLdapServerContextSourceFactoryBean 配置嵌入式 LDAP 服务器。这样会指示 Spring Security 启动内存内 LDAP 服务器:

You can then configure the Embedded LDAP Server using an EmbeddedLdapServerContextSourceFactoryBean. This will instruct Spring Security to start an in-memory LDAP server:

Embedded LDAP Server Configuration
  • Java

  • Kotlin

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

或者,您可以手动配置嵌入式 LDAP 服务器。如果您选择这种方法,您将负责管理嵌入式 LDAP 服务器的生命周期。

Alternatively, you can manually configure the Embedded LDAP Server. If you choose this approach, you will be responsible for managing the lifecycle of the Embedded LDAP Server.

Explicit Embedded LDAP Server Configuration
  • 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")
}

Embedded ApacheDS Server

Spring Security 使用 ApacheDS 1.x,后者不再维护。遗憾的是,ApacheDS 2.x 仅发布了里程碑版本,而不存在任何稳定版本。一旦有 ApacheDS 2.x 的稳定版本可用,我们将会考虑进行更新。

Spring Security uses ApacheDS 1.x, which is no longer maintained. Unfortunately, ApacheDS 2.x has only released milestone versions with no stable release. Once a stable release of ApacheDS 2.x is available, we will consider updating.

如果您希望使用 Apache DS,请指定以下依赖项:

If you wish to use Apache DS, specify the following dependencies:

ApacheDS Dependencies
  • Maven

  • Gradle

<dependency>
	<groupId>org.apache.directory.server</groupId>
	<artifactId>apacheds-core</artifactId>
	<version>{apacheds-core-version}</version>
	<scope>runtime</scope>
</dependency>
<dependency>
	<groupId>org.apache.directory.server</groupId>
	<artifactId>apacheds-server-jndi</artifactId>
	<version>{apacheds-core-version}</version>
	<scope>runtime</scope>
</dependency>
depenendencies {
	runtimeOnly "org.apache.directory.server:apacheds-core:{apacheds-core-version}"
	runtimeOnly "org.apache.directory.server:apacheds-server-jndi:{apacheds-core-version}"
}

然后,您可以配置嵌入式 LDAP 服务器:

You can then configure the Embedded LDAP Server:

Embedded LDAP Server Configuration
  • 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 ContextSource 以指向嵌入式 LDAP 服务器。

Once you have an LDAP Server to which to point your configuration, you need to configure Spring Security to point to an LDAP server that should be used to authenticate users. To do so, create an LDAP ContextSource (which is the equivalent of a JDBC DataSource). If you have already configured an EmbeddedLdapServerContextSourceFactoryBean, Spring Security will create an LDAP ContextSource that points to the embedded LDAP server.

LDAP Context Source with Embedded LDAP Server
  • 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 服务器:

Alternatively, you can explicitly configure the LDAP ContextSource to connect to the supplied LDAP server:

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

Authentication

Spring Security 的 LDAP 支持不使用 UserDetailsService,因为 LDAP 绑定身份验证不允许客户端读取密码,甚至不允许读取密码的哈希版本。这意味着 Spring Security 无法读取密码,进而无法对密码进行身份验证。

Spring Security’s LDAP support does not use the UserDetailsService because LDAP bind authentication does not let clients read the password or even a hashed version of the password. This means there is no way for a password to be read and then authenticated by Spring Security.

出于这个原因,LDAP 支持是通过 LdapAuthenticator 接口实现的。LdapAuthenticator 接口还负责检索任何必需的用户属性。这是因为属性的权限可能取决于所使用的验证类型。例如,如果绑定为该用户,则可能需要以用户的自身权限读取该属性。

For this reason, LDAP support is implemented through the LdapAuthenticator interface. The LdapAuthenticator interface is also responsible for retrieving any required user attributes. This is because the permissions on the attributes may depend on the type of authentication being used. For example, if binding as the user, it may be necessary to read the attributes with the user’s own permissions.

Spring Security 提供了两个 LdapAuthenticator 实现:

Spring Security supplies two LdapAuthenticator implementations:

Using Bind Authentication

Bind Authentication 是使用 LDAP 对用户进行认证的最常见机制。在绑定认证中,用户凭证(用户名和密码)提交至对它们进行认证的 LDAP 服务器。使用绑定认证的优势在于无需对客户端公开用户的秘密(密码),这有助于防止泄露这些秘密。

Bind Authentication is the most common mechanism for authenticating users with LDAP. In bind authentication, the user’s credentials (username and password) are submitted to the LDAP server, which authenticates them. The advantage to using bind authentication is that the user’s secrets (the password) do not need to be exposed to clients, which helps to protect them from leaking.

以下示例显示了绑定验证配置:

The following example shows bind authentication configuration:

Bind Authentication
  • 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 搜索过滤器以查找用户,则可以使用以下内容:

The preceding simple example would obtain the DN for the user by substituting the user login name in the supplied pattern and attempting to bind as that user with the login password. This is OK if all your users are stored under a single node in the directory. If, instead, you wish to configure an LDAP search filter to locate the user, you could use the following:

Bind Authentication with Search Filter
  • 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 definition shown earlier 一起使用,这将使用 (uid={0}) 作为筛选器来在 DN ou=people,dc=springframework,dc=org 下执行搜索。同样地,用户登录名将被替换为筛选器名称中的参数,以便搜索 uid 属性等于用户名的一项条目。如果未提供用户搜索基础,那么从根目录执行搜索。

If used with the ContextSource servlet-authentication-ldap-contextsource, this would perform a search under the DN ou=people,dc=springframework,dc=org by using (uid={0}) as a filter. Again, the user login name is substituted for the parameter in the filter name, so it searches for an entry with the uid attribute equal to the user name. If a user search base is not supplied, the search is performed from the root.

Using Password Authentication

密码比较是将用户提供的密码与存储在存储库中的密码进行比较。可以通过检索密码属性的值并在本地查看该值或者通过执行 LDAP “compare” 操作来实现,其中已提供的密码传递给服务器用于比较而不会检索实际密码值。如果密码使用随机盐正确进行了哈希处理,则无法执行 LDAP 比较。

Password comparison is when the password supplied by the user is compared with the one stored in the repository. This can either be done by retrieving the value of the password attribute and checking it locally or by performing an LDAP “compare” operation, where the supplied password is passed to the server for comparison and the real password value is never retrieved. An LDAP compare cannot be done when the password is properly hashed with a random salt.

Minimal Password Compare Configuration
  • 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()
}

以下示例显示了具有一些自定义的更多高级配置:

The following example shows a more advanced configuration with some customizations:

Password Compare Configuration
  • 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 Specify the password attribute as pwd.

LdapAuthoritiesPopulator

Spring Security 的 LdapAuthoritiesPopulator 用于确定为用户返回哪些权限。以下示例显示了如何配置 LdapAuthoritiesPopulator

Spring Security’s LdapAuthoritiesPopulator is used to determine what authorities are returned for the user. The following example shows how configure LdapAuthoritiesPopulator:

LdapAuthoritiesPopulator Configuration
  • 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 设置自定义的认证提供者。

Active Directory supports its own non-standard authentication options, and the normal usage pattern does not fit too cleanly with the standard LdapAuthenticationProvider. Typically, authentication is performed by using the domain username (in the form of user@domain), rather than using an LDAP distinguished name. To make this easier, Spring Security has an authentication provider, which is customized for a typical Active Directory setup.

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

Configuring ActiveDirectoryLdapAuthenticationProvider is quite straightforward. You need only supply the domain name and an LDAP URL that supplies the address of the server.

还可以使用 DNS 查找来获取服务器的 IP 地址。这目前尚不受支持,但未来版本中可能会支持。

It is also possible to obtain the server’s IP address by using a DNS lookup. This is not currently supported, but hopefully will be in a future version.

下列示例配置活动目录:

The following example configures Active Directory:

Example Active Directory Configuration
  • 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/")
}