ldap.adoc 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. [[servlet-authentication-ldap]]
  2. = LDAP Authentication
  3. LDAP (Lightweight Directory Access Protocol) is often used by organizations as a central repository for user information and as an authentication service.
  4. It can also be used to store the role information for application users.
  5. 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.
  6. 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.
  7. There are many different scenarios for how an LDAP server can be configured, so Spring Security's LDAP provider is fully configurable.
  8. 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.
  9. [[servlet-authentication-ldap-prerequisites]]
  10. == Prerequisites
  11. You should be familiar with LDAP before trying to use it with Spring Security.
  12. 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/.
  13. Some familiarity with the JNDI APIs used to access LDAP from Java can also be useful.
  14. 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.
  15. When using LDAP authentication, you should ensure that you properly configure LDAP connection pooling.
  16. 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].
  17. // FIXME:
  18. // ldap server
  19. // embedded (both java and xml)
  20. // external
  21. // authentication
  22. // bind
  23. // password
  24. // roles
  25. // search, etc (other APIs)
  26. [[servlet-authentication-ldap-embedded]]
  27. == Setting up an Embedded LDAP Server
  28. The first thing you need to do is to ensure that you have an LDAP Server to which to point your configuration.
  29. For simplicity, it is often best to start with an embedded LDAP Server.
  30. Spring Security supports using either:
  31. * <<servlet-authentication-ldap-unboundid>>
  32. * <<servlet-authentication-ldap-apacheds>>
  33. 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`:
  34. .users.ldif
  35. ====
  36. [source,ldif]
  37. ----
  38. dn: ou=groups,dc=springframework,dc=org
  39. objectclass: top
  40. objectclass: organizationalUnit
  41. ou: groups
  42. dn: ou=people,dc=springframework,dc=org
  43. objectclass: top
  44. objectclass: organizationalUnit
  45. ou: people
  46. dn: uid=admin,ou=people,dc=springframework,dc=org
  47. objectclass: top
  48. objectclass: person
  49. objectclass: organizationalPerson
  50. objectclass: inetOrgPerson
  51. cn: Rod Johnson
  52. sn: Johnson
  53. uid: admin
  54. userPassword: password
  55. dn: uid=user,ou=people,dc=springframework,dc=org
  56. objectclass: top
  57. objectclass: person
  58. objectclass: organizationalPerson
  59. objectclass: inetOrgPerson
  60. cn: Dianne Emu
  61. sn: Emu
  62. uid: user
  63. userPassword: password
  64. dn: cn=user,ou=groups,dc=springframework,dc=org
  65. objectclass: top
  66. objectclass: groupOfNames
  67. cn: user
  68. uniqueMember: uid=admin,ou=people,dc=springframework,dc=org
  69. uniqueMember: uid=user,ou=people,dc=springframework,dc=org
  70. dn: cn=admin,ou=groups,dc=springframework,dc=org
  71. objectclass: top
  72. objectclass: groupOfNames
  73. cn: admin
  74. uniqueMember: uid=admin,ou=people,dc=springframework,dc=org
  75. ----
  76. ====
  77. [[servlet-authentication-ldap-unboundid]]
  78. === Embedded UnboundID Server
  79. If you wish to use https://ldap.com/unboundid-ldap-sdk-for-java/[UnboundID], specify the following dependencies:
  80. .UnboundID Dependencies
  81. ====
  82. .Maven
  83. [source,xml,role="primary",subs="verbatim,attributes"]
  84. ----
  85. <dependency>
  86. <groupId>com.unboundid</groupId>
  87. <artifactId>unboundid-ldapsdk</artifactId>
  88. <version>{unboundid-ldapsdk-version}</version>
  89. <scope>runtime</scope>
  90. </dependency>
  91. ----
  92. .Gradle
  93. [source,groovy,role="secondary",subs="verbatim,attributes"]
  94. ----
  95. depenendencies {
  96. runtimeOnly "com.unboundid:unboundid-ldapsdk:{unboundid-ldapsdk-version}"
  97. }
  98. ----
  99. ====
  100. You can then configure the Embedded LDAP Server:
  101. .Embedded LDAP Server Configuration
  102. ====
  103. .Java
  104. [source,java,role="primary"]
  105. ----
  106. @Bean
  107. UnboundIdContainer ldapContainer() {
  108. return new UnboundIdContainer("dc=springframework,dc=org",
  109. "classpath:users.ldif");
  110. }
  111. ----
  112. .XML
  113. [source,xml,role="secondary"]
  114. ----
  115. <b:bean class="org.springframework.security.ldap.server.UnboundIdContainer"
  116. c:defaultPartitionSuffix="dc=springframework,dc=org"
  117. c:ldif="classpath:users.ldif"/>
  118. ----
  119. .Kotlin
  120. [source,kotlin,role="secondary"]
  121. ----
  122. @Bean
  123. fun ldapContainer(): UnboundIdContainer {
  124. return UnboundIdContainer("dc=springframework,dc=org","classpath:users.ldif")
  125. }
  126. ----
  127. ====
  128. [[servlet-authentication-ldap-apacheds]]
  129. === Embedded ApacheDS Server
  130. [NOTE]
  131. ====
  132. Spring Security uses ApacheDS 1.x, which is no longer maintained.
  133. Unfortunately, ApacheDS 2.x has only released milestone versions with no stable release.
  134. Once a stable release of ApacheDS 2.x is available, we will consider updating.
  135. ====
  136. If you wish to use https://directory.apache.org/apacheds/[Apache DS], specify the following dependencies:
  137. .ApacheDS Dependencies
  138. ====
  139. .Maven
  140. [source,xml,role="primary",subs="+attributes"]
  141. ----
  142. <dependency>
  143. <groupId>org.apache.directory.server</groupId>
  144. <artifactId>apacheds-core</artifactId>
  145. <version>{apacheds-core-version}</version>
  146. <scope>runtime</scope>
  147. </dependency>
  148. <dependency>
  149. <groupId>org.apache.directory.server</groupId>
  150. <artifactId>apacheds-server-jndi</artifactId>
  151. <version>{apacheds-core-version}</version>
  152. <scope>runtime</scope>
  153. </dependency>
  154. ----
  155. .Gradle
  156. [source,groovy,role="secondary",subs="+attributes"]
  157. ----
  158. depenendencies {
  159. runtimeOnly "org.apache.directory.server:apacheds-core:{apacheds-core-version}"
  160. runtimeOnly "org.apache.directory.server:apacheds-server-jndi:{apacheds-core-version}"
  161. }
  162. ----
  163. ====
  164. You can then configure the Embedded LDAP Server:
  165. .Embedded LDAP Server Configuration
  166. ====
  167. .Java
  168. [source,java,role="primary"]
  169. ----
  170. @Bean
  171. ApacheDSContainer ldapContainer() {
  172. return new ApacheDSContainer("dc=springframework,dc=org",
  173. "classpath:users.ldif");
  174. }
  175. ----
  176. .XML
  177. [source,xml,role="secondary"]
  178. ----
  179. <b:bean class="org.springframework.security.ldap.server.ApacheDSContainer"
  180. c:defaultPartitionSuffix="dc=springframework,dc=org"
  181. c:ldif="classpath:users.ldif"/>
  182. ----
  183. .Kotlin
  184. [source,kotlin,role="secondary"]
  185. ----
  186. @Bean
  187. fun ldapContainer(): ApacheDSContainer {
  188. return ApacheDSContainer("dc=springframework,dc=org", "classpath:users.ldif")
  189. }
  190. ----
  191. ====
  192. [[servlet-authentication-ldap-contextsource]]
  193. == LDAP ContextSource
  194. 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.
  195. To do so, create an LDAP `ContextSource` (which is the equivalent of a JDBC `DataSource`):
  196. .LDAP Context Source
  197. ====
  198. .Java
  199. [source,java,role="primary"]
  200. ----
  201. ContextSource contextSource(UnboundIdContainer container) {
  202. return new DefaultSpringSecurityContextSource("ldap://localhost:53389/dc=springframework,dc=org");
  203. }
  204. ----
  205. .XML
  206. [source,xml,role="secondary"]
  207. ----
  208. <ldap-server
  209. url="ldap://localhost:53389/dc=springframework,dc=org" />
  210. ----
  211. .Kotlin
  212. [source,kotlin,role="secondary"]
  213. ----
  214. fun contextSource(container: UnboundIdContainer): ContextSource {
  215. return DefaultSpringSecurityContextSource("ldap://localhost:53389/dc=springframework,dc=org")
  216. }
  217. ----
  218. ====
  219. [[servlet-authentication-ldap-authentication]]
  220. == Authentication
  221. 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.
  222. This means there is no way for a password to be read and then authenticated by Spring Security.
  223. For this reason, LDAP support is implemented through the `LdapAuthenticator` interface.
  224. The `LdapAuthenticator` interface is also responsible for retrieving any required user attributes.
  225. This is because the permissions on the attributes may depend on the type of authentication being used.
  226. For example, if binding as the user, it may be necessary to read the attributes with the user's own permissions.
  227. Spring Security supplies two `LdapAuthenticator` implementations:
  228. * <<servlet-authentication-ldap-bind>>
  229. * <<servlet-authentication-ldap-pwd>>
  230. [[servlet-authentication-ldap-bind]]
  231. == Using Bind Authentication
  232. https://ldap.com/the-ldap-bind-operation/[Bind Authentication] is the most common mechanism for authenticating users with LDAP.
  233. In bind authentication, the user's credentials (username and password) are submitted to the LDAP server, which authenticates them.
  234. 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.
  235. The following example shows bind authentication configuration:
  236. .Bind Authentication
  237. ====
  238. .Java
  239. [source,java,role="primary",attrs="-attributes"]
  240. ----
  241. @Bean
  242. BindAuthenticator authenticator(BaseLdapPathContextSource contextSource) {
  243. BindAuthenticator authenticator = new BindAuthenticator(contextSource);
  244. authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" });
  245. return authenticator;
  246. }
  247. @Bean
  248. LdapAuthenticationProvider authenticationProvider(LdapAuthenticator authenticator) {
  249. return new LdapAuthenticationProvider(authenticator);
  250. }
  251. ----
  252. .XML
  253. [source,xml,role="secondary",attrs="-attributes"]
  254. ----
  255. <ldap-authentication-provider
  256. user-dn-pattern="uid={0},ou=people"/>
  257. ----
  258. .Kotlin
  259. [source,kotlin,role="secondary",attrs="-attributes"]
  260. ----
  261. @Bean
  262. fun authenticator(contextSource: BaseLdapPathContextSource): BindAuthenticator {
  263. val authenticator = BindAuthenticator(contextSource)
  264. authenticator.setUserDnPatterns(arrayOf("uid={0},ou=people"))
  265. return authenticator
  266. }
  267. @Bean
  268. fun authenticationProvider(authenticator: LdapAuthenticator): LdapAuthenticationProvider {
  269. return LdapAuthenticationProvider(authenticator)
  270. }
  271. ----
  272. ====
  273. 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.
  274. This is OK if all your users are stored under a single node in the directory.
  275. If, instead, you wish to configure an LDAP search filter to locate the user, you could use the following:
  276. .Bind Authentication with Search Filter
  277. ====
  278. .Java
  279. [source,java,role="primary",attrs="-attributes"]
  280. ----
  281. @Bean
  282. BindAuthenticator authenticator(BaseLdapPathContextSource contextSource) {
  283. String searchBase = "ou=people";
  284. String filter = "(uid={0})";
  285. FilterBasedLdapUserSearch search =
  286. new FilterBasedLdapUserSearch(searchBase, filter, contextSource);
  287. BindAuthenticator authenticator = new BindAuthenticator(contextSource);
  288. authenticator.setUserSearch(search);
  289. return authenticator;
  290. }
  291. @Bean
  292. LdapAuthenticationProvider authenticationProvider(LdapAuthenticator authenticator) {
  293. return new LdapAuthenticationProvider(authenticator);
  294. }
  295. ----
  296. .XML
  297. [source,xml,role="secondary",attrs="-attributes"]
  298. ----
  299. <ldap-authentication-provider
  300. user-search-filter="(uid={0})"
  301. user-search-base="ou=people"/>
  302. ----
  303. .Kotlin
  304. [source,kotlin,role="secondary",attrs="-attributes"]
  305. ----
  306. @Bean
  307. fun authenticator(contextSource: BaseLdapPathContextSource): BindAuthenticator {
  308. val searchBase = "ou=people"
  309. val filter = "(uid={0})"
  310. val search = FilterBasedLdapUserSearch(searchBase, filter, contextSource)
  311. val authenticator = BindAuthenticator(contextSource)
  312. authenticator.setUserSearch(search)
  313. return authenticator
  314. }
  315. @Bean
  316. fun authenticationProvider(authenticator: LdapAuthenticator): LdapAuthenticationProvider {
  317. return LdapAuthenticationProvider(authenticator)
  318. }
  319. ----
  320. ====
  321. 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.
  322. 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.
  323. If a user search base is not supplied, the search is performed from the root.
  324. [[servlet-authentication-ldap-pwd]]
  325. == Using Password Authentication
  326. Password comparison is when the password supplied by the user is compared with the one stored in the repository.
  327. 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.
  328. An LDAP compare cannot be done when the password is properly hashed with a random salt.
  329. .Minimal Password Compare Configuration
  330. ====
  331. .Java
  332. [source,java,role="primary"]
  333. ----
  334. @Bean
  335. PasswordComparisonAuthenticator authenticator(BaseLdapPathContextSource contextSource) {
  336. return new PasswordComparisonAuthenticator(contextSource);
  337. }
  338. @Bean
  339. LdapAuthenticationProvider authenticationProvider(LdapAuthenticator authenticator) {
  340. return new LdapAuthenticationProvider(authenticator);
  341. }
  342. ----
  343. .XML
  344. [source,xml,role="secondary",attrs="-attributes"]
  345. ----
  346. <ldap-authentication-provider
  347. user-dn-pattern="uid={0},ou=people">
  348. <password-compare />
  349. </ldap-authentication-provider>
  350. ----
  351. .Kotlin
  352. [source,kotlin,role="secondary"]
  353. ----
  354. @Bean
  355. fun authenticator(contextSource: BaseLdapPathContextSource): PasswordComparisonAuthenticator {
  356. return PasswordComparisonAuthenticator(contextSource)
  357. }
  358. @Bean
  359. fun authenticationProvider(authenticator: LdapAuthenticator): LdapAuthenticationProvider {
  360. return LdapAuthenticationProvider(authenticator)
  361. }
  362. ----
  363. ====
  364. The following example shows a more advanced configuration with some customizations:
  365. .Password Compare Configuration
  366. ====
  367. .Java
  368. [source,java,role="primary"]
  369. ----
  370. @Bean
  371. PasswordComparisonAuthenticator authenticator(BaseLdapPathContextSource contextSource) {
  372. PasswordComparisonAuthenticator authenticator =
  373. new PasswordComparisonAuthenticator(contextSource);
  374. authenticator.setPasswordAttributeName("pwd"); // <1>
  375. authenticator.setPasswordEncoder(new BCryptPasswordEncoder()); // <2>
  376. return authenticator;
  377. }
  378. @Bean
  379. LdapAuthenticationProvider authenticationProvider(LdapAuthenticator authenticator) {
  380. return new LdapAuthenticationProvider(authenticator);
  381. }
  382. ----
  383. .XML
  384. [source,xml,role="secondary",attrs="-attributes"]
  385. ----
  386. <ldap-authentication-provider
  387. user-dn-pattern="uid={0},ou=people">
  388. <password-compare password-attribute="pwd"> <!--1-->
  389. <password-encoder ref="passwordEncoder" /> <!--2-->
  390. </password-compare>
  391. </ldap-authentication-provider>
  392. <b:bean id="passwordEncoder"
  393. class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
  394. ----
  395. .Kotlin
  396. [source,kotlin,role="secondary"]
  397. ----
  398. @Bean
  399. fun authenticator(contextSource: BaseLdapPathContextSource): PasswordComparisonAuthenticator {
  400. val authenticator = PasswordComparisonAuthenticator(contextSource)
  401. authenticator.setPasswordAttributeName("pwd") // <1>
  402. authenticator.setPasswordEncoder(BCryptPasswordEncoder()) // <2>
  403. return authenticator
  404. }
  405. @Bean
  406. fun authenticationProvider(authenticator: LdapAuthenticator): LdapAuthenticationProvider {
  407. return LdapAuthenticationProvider(authenticator)
  408. }
  409. ----
  410. ====
  411. <1> Specify the password attribute as `pwd`.
  412. <2> Use `BCryptPasswordEncoder`.
  413. == LdapAuthoritiesPopulator
  414. Spring Security's `LdapAuthoritiesPopulator` is used to determine what authorities are returned for the user.
  415. The following example shows how configure `LdapAuthoritiesPopulator`:
  416. .LdapAuthoritiesPopulator Configuration
  417. ====
  418. .Java
  419. [source,java,role="primary",attrs="-attributes"]
  420. ----
  421. @Bean
  422. LdapAuthoritiesPopulator authorities(BaseLdapPathContextSource contextSource) {
  423. String groupSearchBase = "";
  424. DefaultLdapAuthoritiesPopulator authorities =
  425. new DefaultLdapAuthoritiesPopulator(contextSource, groupSearchBase);
  426. authorities.setGroupSearchFilter("member={0}");
  427. return authorities;
  428. }
  429. @Bean
  430. LdapAuthenticationProvider authenticationProvider(LdapAuthenticator authenticator, LdapAuthoritiesPopulator authorities) {
  431. return new LdapAuthenticationProvider(authenticator, authorities);
  432. }
  433. ----
  434. .XML
  435. [source,xml,role="secondary",attrs="-attributes"]
  436. ----
  437. <ldap-authentication-provider
  438. user-dn-pattern="uid={0},ou=people"
  439. group-search-filter="member={0}"/>
  440. ----
  441. .Kotlin
  442. [source,kotlin,role="secondary",attrs="-attributes"]
  443. ----
  444. @Bean
  445. fun authorities(contextSource: BaseLdapPathContextSource): LdapAuthoritiesPopulator {
  446. val groupSearchBase = ""
  447. val authorities = DefaultLdapAuthoritiesPopulator(contextSource, groupSearchBase)
  448. authorities.setGroupSearchFilter("member={0}")
  449. return authorities
  450. }
  451. @Bean
  452. fun authenticationProvider(authenticator: LdapAuthenticator, authorities: LdapAuthoritiesPopulator): LdapAuthenticationProvider {
  453. return LdapAuthenticationProvider(authenticator, authorities)
  454. }
  455. ----
  456. ====
  457. == Active Directory
  458. Active Directory supports its own non-standard authentication options, and the normal usage pattern does not fit too cleanly with the standard `LdapAuthenticationProvider`.
  459. Typically, authentication is performed by using the domain username (in the form of `user@domain`), rather than using an LDAP distinguished name.
  460. To make this easier, Spring Security has an authentication provider, which is customized for a typical Active Directory setup.
  461. Configuring `ActiveDirectoryLdapAuthenticationProvider` is quite straightforward.
  462. You need only supply the domain name and an LDAP URL that supplies the address of the server.
  463. [NOTE]
  464. ====
  465. It is also possible to obtain the server's IP address byusing a DNS lookup.
  466. This is not currently supported, but hopefully will be in a future version.
  467. ====
  468. The following example configures Active Directory:
  469. .Example Active Directory Configuration
  470. ====
  471. .Java
  472. [source,java,role="primary"]
  473. ----
  474. @Bean
  475. ActiveDirectoryLdapAuthenticationProvider authenticationProvider() {
  476. return new ActiveDirectoryLdapAuthenticationProvider("example.com", "ldap://company.example.com/");
  477. }
  478. ----
  479. .XML
  480. [source,xml,role="secondary"]
  481. ----
  482. <bean id="authenticationProvider"
  483. class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
  484. <constructor-arg value="example.com" />
  485. <constructor-arg value="ldap://company.example.com/" />
  486. </bean>
  487. ----
  488. .Kotlin
  489. [source,kotlin,role="secondary"]
  490. ----
  491. @Bean
  492. fun authenticationProvider(): ActiveDirectoryLdapAuthenticationProvider {
  493. return ActiveDirectoryLdapAuthenticationProvider("example.com", "ldap://company.example.com/")
  494. }
  495. ----
  496. ====