ldap.adoc 18 KB

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