servlet-authentication-passwords-storage-ldap.md 17.3 KB
Newer Older
茶陵後's avatar
茶陵後 已提交
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
# LDAP Authentication

LDAP 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 [accept a username/password](index.html#servlet-authentication-unpwd-input) for authentication.
However, despite leveraging a username/password for authentication it does not integrate using `UserDetailsService` because in [bind authentication](#servlet-authentication-ldap-bind) 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 may 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

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/](https://www.zytrax.com/books/ldap/).
Some familiarity with the JNDI APIs used to access LDAP from Java may also be useful.
We don’t use any third-party LDAP libraries (Mozilla, JLDAP etc.) 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, it is important to ensure that you configure LDAP connection pooling properly.
If you are unfamiliar with how to do this, you can refer to the [Java LDAP documentation](https://docs.oracle.com/javase/jndi/tutorial/ldap/connect/config.html).

## Setting up an Embedded LDAP Server

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

* [Embedded UnboundID Server](#servlet-authentication-ldap-unboundid)

* [Embedded ApacheDS Server](#servlet-authentication-ldap-apacheds)

In the samples below, we expose the following as `users.ldif` as a classpath resource to initialize the embedded LDAP server with the 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

If you wish to use [UnboundID](https://ldap.com/unboundid-ldap-sdk-for-java/), then specify the following dependencies:

Example 1. UnboundID Dependencies

Maven

```
<dependency>
	<groupId>com.unboundid</groupId>
	<artifactId>unboundid-ldapsdk</artifactId>
	<version>4.0.14</version>
	<scope>runtime</scope>
</dependency>
```

Gradle

```
depenendencies {
	runtimeOnly "com.unboundid:unboundid-ldapsdk:4.0.14"
}
```

You can then configure the Embedded LDAP Server

Example 2. Embedded LDAP Server Configuration

Java

```
@Bean
UnboundIdContainer ldapContainer() {
	return new UnboundIdContainer("dc=springframework,dc=org",
				"classpath:users.ldif");
}
```

XML

```
<b:bean class="org.springframework.security.ldap.server.UnboundIdContainer"
	c:defaultPartitionSuffix="dc=springframework,dc=org"
	c:ldif="classpath:users.ldif"/>
```

Kotlin

```
@Bean
fun ldapContainer(): UnboundIdContainer {
    return UnboundIdContainer("dc=springframework,dc=org","classpath:users.ldif")
}
```

### Embedded ApacheDS Server

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

If you wish to use [Apache DS](https://directory.apache.org/apacheds/), then specify the following dependencies:

Example 3. ApacheDS Dependencies

Maven

```
<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>
```

Gradle

```
depenendencies {
	runtimeOnly "org.apache.directory.server:apacheds-core:1.5.5"
	runtimeOnly "org.apache.directory.server:apacheds-server-jndi:1.5.5"
}
```

You can then configure the Embedded LDAP Server

Example 4. Embedded LDAP Server Configuration

Java

```
@Bean
ApacheDSContainer ldapContainer() {
	return new ApacheDSContainer("dc=springframework,dc=org",
				"classpath:users.ldif");
}
```

XML

```
<b:bean class="org.springframework.security.ldap.server.ApacheDSContainer"
	c:defaultPartitionSuffix="dc=springframework,dc=org"
	c:ldif="classpath:users.ldif"/>
```

Kotlin

```
@Bean
fun ldapContainer(): ApacheDSContainer {
    return ApacheDSContainer("dc=springframework,dc=org", "classpath:users.ldif")
}
```

## LDAP ContextSource

Once you have an LDAP Server to point your configuration to, you need configure Spring Security to point to an LDAP server that should be used to authenticate users.
This is done by creating an LDAP `ContextSource`, which is the equivalent of a JDBC `DataSource`.

Example 5. LDAP Context Source

Java

```
ContextSource contextSource(UnboundIdContainer container) {
	return new DefaultSpringSecurityContextSource("ldap://localhost:53389/dc=springframework,dc=org");
}
```

XML

```
<ldap-server
	url="ldap://localhost:53389/dc=springframework,dc=org" />
```

Kotlin

```
fun contextSource(container: UnboundIdContainer): ContextSource {
    return DefaultSpringSecurityContextSource("ldap://localhost:53389/dc=springframework,dc=org")
}
```

## Authentication

Spring Security’s LDAP support does not use the [UserDetailsService](user-details-service.html#servlet-authentication-userdetailsservice) because LDAP bind authentication does not allow clients to read the password or even a hashed version of the password.
This means there is no way a password to be read and then authenticated by Spring Security.

For this reason, LDAP support is implemented using the `LdapAuthenticator` interface.
The `LdapAuthenticator` 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 them with the user’s own permissions.

There are two `LdapAuthenticator` implementations supplied with Spring Security:

* [Using Bind Authentication](#servlet-authentication-ldap-bind)

* [Using Password Authentication](#servlet-authentication-ldap-pwd)

## Using Bind Authentication

[Bind Authentication](https://ldap.com/the-ldap-bind-operation/) is the most common mechanism for authenticating users with LDAP.
In bind authentication the users credentials (i.e. username/password) are submitted to the LDAP server which authenticates them.
The advantage to using bind authentication is that the user’s secrets (i.e. password) do not need to be exposed to clients which helps to protect them from leaking.

An example of bind authentication configuration can be found below.

Example 6. Bind Authentication

Java

```
@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

```
<ldap-authentication-provider
	user-dn-pattern="uid={0},ou=people"/>
```

Kotlin

```
@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)
}
```

This 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 wished to configure an LDAP search filter to locate the user, you could use the following:

Example 7. Bind Authentication with Search Filter

Java

```
@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

```
<ldap-authentication-provider
		user-search-filter="(uid={0})"
	user-search-base="ou=people"/>
```

Kotlin

```
@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` [definition above](#servlet-authentication-ldap-contextsource), this would perform a search under the DN `ou=people,dc=springframework,dc=org` using `(uid={0})` as a filter.
Again the user login name is substituted for the parameter in the filter name, so it will search for an entry with the `uid` attribute equal to the user name.
If a user search base isn’t supplied, the search will be performed from the root.

## 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.

Example 8. Minimal Password Compare Configuration

Java

```
@Bean
PasswordComparisonAuthenticator authenticator(BaseLdapPathContextSource contextSource) {
	return new PasswordComparisonAuthenticator(contextSource);
}

@Bean
LdapAuthenticationProvider authenticationProvider(LdapAuthenticator authenticator) {
	return new LdapAuthenticationProvider(authenticator);
}
```

XML

```
<ldap-authentication-provider
		user-dn-pattern="uid={0},ou=people">
	<password-compare />
</ldap-authentication-provider>
```

Kotlin

```
@Bean
fun authenticator(contextSource: BaseLdapPathContextSource): PasswordComparisonAuthenticator {
    return PasswordComparisonAuthenticator(contextSource)
}

@Bean
fun authenticationProvider(authenticator: LdapAuthenticator): LdapAuthenticationProvider {
    return LdapAuthenticationProvider(authenticator)
}
```

A more advanced configuration with some customizations can be found below.

Example 9. Password Compare Configuration

Java

```
@Bean
PasswordComparisonAuthenticator authenticator(BaseLdapPathContextSource contextSource) {
	PasswordComparisonAuthenticator authenticator =
		new PasswordComparisonAuthenticator(contextSource);
	authenticator.setPasswordAttributeName("pwd"); (1)
	authenticator.setPasswordEncoder(new BCryptPasswordEncoder()); (2)
	return authenticator;
}

@Bean
LdapAuthenticationProvider authenticationProvider(LdapAuthenticator authenticator) {
	return new LdapAuthenticationProvider(authenticator);
}
```

XML

```
<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

```
@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)
}
```

|**1**|Specify the password attribute as `pwd`|
|-----|---------------------------------------|
|**2**|      Use `BCryptPasswordEncoder`      |

## LdapAuthoritiesPopulator

Spring Security’s `LdapAuthoritiesPopulator` is used to determine what authorites are returned for the user.

Example 10. LdapAuthoritiesPopulator Configuration

Java

```
@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

```
<ldap-authentication-provider
	user-dn-pattern="uid={0},ou=people"
	group-search-filter="member={0}"/>
```

Kotlin

```
@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 doesn’t fit too cleanly with the standard `LdapAuthenticationProvider`.
Typically authentication is performed using the domain username (in the form `[[email protected]](/cdn-cgi/l/email-protection)`), 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 just need to supply the domain name and an LDAP URL supplying the address of the server <sup class="footnote">[<a id="_footnoteref_1" class="footnote" href="#_footnotedef_1" title="View footnote.">1</a>]</sup>.
An example configuration can be seen below:

Example 11. Example Active Directory Configuration

Java

```
@Bean
ActiveDirectoryLdapAuthenticationProvider authenticationProvider() {
	return new ActiveDirectoryLdapAuthenticationProvider("example.com", "ldap://company.example.com/");
}
```

XML

```
<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

```
@Bean
fun authenticationProvider(): ActiveDirectoryLdapAuthenticationProvider {
    return ActiveDirectoryLdapAuthenticationProvider("example.com", "ldap://company.example.com/")
}
```

---

[1](#_footnoteref_1). It is also possible to obtain the server’s IP address using a DNS lookup. This is not currently supported, but hopefully will be in a future version.

[DaoAuthenticationProvider](dao-authentication-provider.html)[Session Management](../session-management.html)