spring-security/docs/modules/ROOT/pages/servlet/authentication/passwords/ldap.adoc

587 lines
19 KiB
Plaintext
Raw Normal View History

[[servlet-authentication-ldap]]
= LDAP Authentication
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's LDAP-based authentication is used by Spring Security when it is configured to xref:servlet/authentication/passwords/index.adoc#servlet-authentication-unpwd-input[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,bind authentication>>, the LDAP server does not return the password, so the application cannot perform validation of the password.
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.
[[servlet-authentication-ldap-prerequisites]]
== Prerequisites
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: 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.
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 https://docs.oracle.com/javase/jndi/tutorial/ldap/connect/config.html[Java LDAP documentation].
// FIXME:
// ldap server
// embedded (both java and xml)
// external
// authentication
// bind
// password
// roles
// search, etc (other APIs)
[[servlet-authentication-ldap-embedded]]
== Setting up an Embedded LDAP Server
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:
* <<servlet-authentication-ldap-unboundid>>
* <<servlet-authentication-ldap-apacheds>>
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
====
[source,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
----
====
[[servlet-authentication-ldap-unboundid]]
=== Embedded UnboundID Server
If you wish to use https://ldap.com/unboundid-ldap-sdk-for-java/[UnboundID], specify the following dependencies:
.UnboundID Dependencies
====
.Maven
[source,xml,role="primary",subs="verbatim,attributes"]
----
<dependency>
<groupId>com.unboundid</groupId>
<artifactId>unboundid-ldapsdk</artifactId>
<version>{unboundid-ldapsdk-version}</version>
<scope>runtime</scope>
</dependency>
----
.Gradle
[source,groovy,role="secondary",subs="verbatim,attributes"]
----
depenendencies {
runtimeOnly "com.unboundid:unboundid-ldapsdk:{unboundid-ldapsdk-version}"
}
----
====
You can then configure the Embedded LDAP Server:
.Embedded LDAP Server Configuration
====
.Java
[source,java,role="primary"]
----
@Bean
UnboundIdContainer ldapContainer() {
return new UnboundIdContainer("dc=springframework,dc=org",
"classpath:users.ldif");
}
----
.XML
[source,xml,role="secondary"]
----
<b:bean class="org.springframework.security.ldap.server.UnboundIdContainer"
c:defaultPartitionSuffix="dc=springframework,dc=org"
c:ldif="classpath:users.ldif"/>
----
.Kotlin
[source,kotlin,role="secondary"]
----
@Bean
fun ldapContainer(): UnboundIdContainer {
return UnboundIdContainer("dc=springframework,dc=org","classpath:users.ldif")
}
----
====
[[servlet-authentication-ldap-apacheds]]
=== Embedded ApacheDS Server
[NOTE]
====
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.
====
If you wish to use https://directory.apache.org/apacheds/[Apache DS], specify the following dependencies:
.ApacheDS Dependencies
====
.Maven
[source,xml,role="primary",subs="+attributes"]
----
<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>
----
.Gradle
[source,groovy,role="secondary",subs="+attributes"]
----
depenendencies {
runtimeOnly "org.apache.directory.server:apacheds-core:{apacheds-core-version}"
runtimeOnly "org.apache.directory.server:apacheds-server-jndi:{apacheds-core-version}"
}
----
====
You can then configure the Embedded LDAP Server:
.Embedded LDAP Server Configuration
====
.Java
[source,java,role="primary"]
----
@Bean
ApacheDSContainer ldapContainer() {
return new ApacheDSContainer("dc=springframework,dc=org",
"classpath:users.ldif");
}
----
.XML
[source,xml,role="secondary"]
----
<b:bean class="org.springframework.security.ldap.server.ApacheDSContainer"
c:defaultPartitionSuffix="dc=springframework,dc=org"
c:ldif="classpath:users.ldif"/>
----
.Kotlin
[source,kotlin,role="secondary"]
----
@Bean
fun ldapContainer(): ApacheDSContainer {
return ApacheDSContainer("dc=springframework,dc=org", "classpath:users.ldif")
}
----
====
[[servlet-authentication-ldap-contextsource]]
== LDAP ContextSource
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`):
.LDAP Context Source
====
.Java
[source,java,role="primary"]
----
ContextSource contextSource(UnboundIdContainer container) {
return new DefaultSpringSecurityContextSource("ldap://localhost:53389/dc=springframework,dc=org");
}
----
.XML
[source,xml,role="secondary"]
----
<ldap-server
url="ldap://localhost:53389/dc=springframework,dc=org" />
----
.Kotlin
[source,kotlin,role="secondary"]
----
fun contextSource(container: UnboundIdContainer): ContextSource {
return DefaultSpringSecurityContextSource("ldap://localhost:53389/dc=springframework,dc=org")
}
----
====
[[servlet-authentication-ldap-authentication]]
== Authentication
Spring Security's LDAP support does not use the xref:servlet/authentication/passwords/user-details-service.adoc#servlet-authentication-userdetailsservice[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.
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 supplies two `LdapAuthenticator` implementations:
* <<servlet-authentication-ldap-bind>>
* <<servlet-authentication-ldap-pwd>>
[[servlet-authentication-ldap-bind]]
== Using Bind Authentication
https://ldap.com/the-ldap-bind-operation/[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
[source,java,role="primary",attrs="-attributes"]
----
@Bean
BindAuthenticator authenticator(BaseLdapPathContextSource contextSource) {
BindAuthenticator authenticator = new BindAuthenticator(contextSource);
authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" });
return authenticator;
}
@Bean
LdapAuthenticationProvider authenticationProvider(LdapAuthenticator authenticator) {
return new LdapAuthenticationProvider(authenticator);
}
----
.XML
[source,xml,role="secondary",attrs="-attributes"]
----
<ldap-authentication-provider
user-dn-pattern="uid={0},ou=people"/>
----
.Kotlin
[source,kotlin,role="secondary",attrs="-attributes"]
----
@Bean
fun authenticator(contextSource: BaseLdapPathContextSource): BindAuthenticator {
val authenticator = BindAuthenticator(contextSource)
authenticator.setUserDnPatterns(arrayOf("uid={0},ou=people"))
return authenticator
}
@Bean
fun authenticationProvider(authenticator: LdapAuthenticator): LdapAuthenticationProvider {
return LdapAuthenticationProvider(authenticator)
}
----
====
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
[source,java,role="primary",attrs="-attributes"]
----
@Bean
BindAuthenticator authenticator(BaseLdapPathContextSource contextSource) {
String searchBase = "ou=people";
String filter = "(uid={0})";
FilterBasedLdapUserSearch search =
new FilterBasedLdapUserSearch(searchBase, filter, contextSource);
BindAuthenticator authenticator = new BindAuthenticator(contextSource);
authenticator.setUserSearch(search);
return authenticator;
}
@Bean
LdapAuthenticationProvider authenticationProvider(LdapAuthenticator authenticator) {
return new LdapAuthenticationProvider(authenticator);
}
----
.XML
[source,xml,role="secondary",attrs="-attributes"]
----
<ldap-authentication-provider
user-search-filter="(uid={0})"
user-search-base="ou=people"/>
----
.Kotlin
[source,kotlin,role="secondary",attrs="-attributes"]
----
@Bean
fun authenticator(contextSource: BaseLdapPathContextSource): BindAuthenticator {
val searchBase = "ou=people"
val filter = "(uid={0})"
val search = FilterBasedLdapUserSearch(searchBase, filter, contextSource)
val authenticator = BindAuthenticator(contextSource)
authenticator.setUserSearch(search)
return authenticator
}
@Bean
fun authenticationProvider(authenticator: LdapAuthenticator): LdapAuthenticationProvider {
return LdapAuthenticationProvider(authenticator)
}
----
====
If used with the `ContextSource` <<servlet-authentication-ldap-contextsource,definition shown earlier>>, 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 searchs 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.
[[servlet-authentication-ldap-pwd]]
== Using Password Authentication
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
[source,java,role="primary"]
----
@Bean
PasswordComparisonAuthenticator authenticator(BaseLdapPathContextSource contextSource) {
return new PasswordComparisonAuthenticator(contextSource);
}
@Bean
LdapAuthenticationProvider authenticationProvider(LdapAuthenticator authenticator) {
return new LdapAuthenticationProvider(authenticator);
}
----
.XML
[source,xml,role="secondary",attrs="-attributes"]
----
<ldap-authentication-provider
user-dn-pattern="uid={0},ou=people">
<password-compare />
</ldap-authentication-provider>
----
.Kotlin
[source,kotlin,role="secondary"]
----
@Bean
fun authenticator(contextSource: BaseLdapPathContextSource): PasswordComparisonAuthenticator {
return PasswordComparisonAuthenticator(contextSource)
}
@Bean
fun authenticationProvider(authenticator: LdapAuthenticator): LdapAuthenticationProvider {
return LdapAuthenticationProvider(authenticator)
}
----
====
2019-09-22 14:56:30 +08:00
The following example shows a more advanced configuration with some customizations:
2019-09-22 14:56:30 +08:00
.Password Compare Configuration
====
.Java
[source,java,role="primary"]
2019-09-22 14:56:30 +08:00
----
@Bean
PasswordComparisonAuthenticator authenticator(BaseLdapPathContextSource contextSource) {
PasswordComparisonAuthenticator authenticator =
new PasswordComparisonAuthenticator(contextSource);
authenticator.setPasswordAttributeName("pwd"); // <1>
authenticator.setPasswordEncoder(new BCryptPasswordEncoder()); // <2>
return authenticator;
}
2019-09-22 14:56:30 +08:00
@Bean
LdapAuthenticationProvider authenticationProvider(LdapAuthenticator authenticator) {
return new LdapAuthenticationProvider(authenticator);
2019-09-22 14:56:30 +08:00
}
----
.XML
[source,xml,role="secondary",attrs="-attributes"]
2019-09-22 14:56:30 +08:00
----
<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" />
----
.Kotlin
[source,kotlin,role="secondary"]
----
@Bean
fun authenticator(contextSource: BaseLdapPathContextSource): PasswordComparisonAuthenticator {
val authenticator = PasswordComparisonAuthenticator(contextSource)
authenticator.setPasswordAttributeName("pwd") // <1>
authenticator.setPasswordEncoder(BCryptPasswordEncoder()) // <2>
return authenticator
}
@Bean
fun authenticationProvider(authenticator: LdapAuthenticator): LdapAuthenticationProvider {
return LdapAuthenticationProvider(authenticator)
}
----
====
2019-09-22 14:56:30 +08:00
<1> Specify the password attribute as `pwd`.
<2> Use `BCryptPasswordEncoder`.
2019-09-22 14:56:30 +08:00
== LdapAuthoritiesPopulator
2019-09-22 14:56:30 +08:00
Spring Security's `LdapAuthoritiesPopulator` is used to determine what authorities are returned for the user.
The following example shows how configure `LdapAuthoritiesPopulator`:
2019-09-22 14:56:30 +08:00
2021-01-29 02:22:02 +08:00
.LdapAuthoritiesPopulator Configuration
====
.Java
[source,java,role="primary",attrs="-attributes"]
2019-09-22 14:56:30 +08:00
----
@Bean
LdapAuthoritiesPopulator authorities(BaseLdapPathContextSource contextSource) {
String groupSearchBase = "";
DefaultLdapAuthoritiesPopulator authorities =
new DefaultLdapAuthoritiesPopulator(contextSource, groupSearchBase);
authorities.setGroupSearchFilter("member={0}");
return authorities;
}
@Bean
LdapAuthenticationProvider authenticationProvider(LdapAuthenticator authenticator, LdapAuthoritiesPopulator authorities) {
return new LdapAuthenticationProvider(authenticator, authorities);
}
----
.XML
[source,xml,role="secondary",attrs="-attributes"]
----
<ldap-authentication-provider
user-dn-pattern="uid={0},ou=people"
group-search-filter="member={0}"/>
----
.Kotlin
[source,kotlin,role="secondary",attrs="-attributes"]
----
@Bean
fun authorities(contextSource: BaseLdapPathContextSource): LdapAuthoritiesPopulator {
val groupSearchBase = ""
val authorities = DefaultLdapAuthoritiesPopulator(contextSource, groupSearchBase)
authorities.setGroupSearchFilter("member={0}")
return authorities
}
@Bean
fun authenticationProvider(authenticator: LdapAuthenticator, authorities: LdapAuthoritiesPopulator): LdapAuthenticationProvider {
return LdapAuthenticationProvider(authenticator, authorities)
}
----
====
== 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.
Configuring `ActiveDirectoryLdapAuthenticationProvider` is quite straightforward.
You need only supply the domain name and an LDAP URL that supplies the address of the server.
[NOTE]
====
It is also possible to obtain the server's IP address byusing 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
[source,java,role="primary"]
----
@Bean
ActiveDirectoryLdapAuthenticationProvider authenticationProvider() {
return new ActiveDirectoryLdapAuthenticationProvider("example.com", "ldap://company.example.com/");
}
----
.XML
[source,xml,role="secondary"]
----
<bean id="authenticationProvider"
class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
<constructor-arg value="example.com" />
<constructor-arg value="ldap://company.example.com/" />
</bean>
----
.Kotlin
[source,kotlin,role="secondary"]
----
@Bean
fun authenticationProvider(): ActiveDirectoryLdapAuthenticationProvider {
return ActiveDirectoryLdapAuthenticationProvider("example.com", "ldap://company.example.com/")
}
----
====