| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650 | [[servlet-authentication-ldap]]= LDAP AuthenticationLDAP 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 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.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.[[servlet-authentication-ldap-prerequisites]]== PrerequisitesYou 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 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 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 ServerThe first thing you will need to do is to ensure that you have an LDAP Server to point your configuration to.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 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[source,ldif]----dn: ou=groups,dc=springframework,dc=orgobjectclass: topobjectclass: organizationalUnitou: groupsdn: ou=people,dc=springframework,dc=orgobjectclass: topobjectclass: organizationalUnitou: peopledn: uid=admin,ou=people,dc=springframework,dc=orgobjectclass: topobjectclass: personobjectclass: organizationalPersonobjectclass: inetOrgPersoncn: Rod Johnsonsn: Johnsonuid: adminuserPassword: passworddn: uid=user,ou=people,dc=springframework,dc=orgobjectclass: topobjectclass: personobjectclass: organizationalPersonobjectclass: inetOrgPersoncn: Dianne Emusn: Emuuid: useruserPassword: passworddn: cn=user,ou=groups,dc=springframework,dc=orgobjectclass: topobjectclass: groupOfNamescn: useruniqueMember: uid=admin,ou=people,dc=springframework,dc=orguniqueMember: uid=user,ou=people,dc=springframework,dc=orgdn: cn=admin,ou=groups,dc=springframework,dc=orgobjectclass: topobjectclass: groupOfNamescn: adminuniqueMember: uid=admin,ou=people,dc=springframework,dc=org----[[servlet-authentication-ldap-unboundid]]=== Embedded UnboundID ServerIf you wish to use https://ldap.com/unboundid-ldap-sdk-for-java/[UnboundID], then specify the following dependencies:.UnboundID Dependencies[tabs]======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 using an `EmbeddedLdapServerContextSourceFactoryBean`.This will instruct Spring Security to start an in-memory LDAP server..Embedded LDAP Server Configuration[tabs]======Java::+[source,java,role="primary"]----@Beanpublic EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() {	return EmbeddedLdapServerContextSourceFactoryBean.fromEmbeddedLdapServer();}----Kotlin::+[source,kotlin,role="secondary"]----@Beanfun contextSourceFactoryBean(): EmbeddedLdapServerContextSourceFactoryBean {    return EmbeddedLdapServerContextSourceFactoryBean.fromEmbeddedLdapServer()}----======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[tabs]======Java::+[source,java,role="primary"]----@BeanUnboundIdContainer 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"]----@Beanfun 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], then specify the following dependencies:.ApacheDS Dependencies[tabs]======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[tabs]======Java::+[source,java,role="primary"]----@BeanApacheDSContainer 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"]----@Beanfun ldapContainer(): ApacheDSContainer {    return ApacheDSContainer("dc=springframework,dc=org", "classpath:users.ldif")}----======[[servlet-authentication-ldap-contextsource]]== LDAP ContextSourceOnce 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`.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[tabs]======Java::+[source,java,role="primary"]----@Beanpublic EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() {	EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean =			EmbeddedLdapServerContextSourceFactoryBean.fromEmbeddedLdapServer();	contextSourceFactoryBean.setPort(0);	return contextSourceFactoryBean;}----Kotlin::+[source,kotlin,role="secondary"]----@Beanfun contextSourceFactoryBean(): EmbeddedLdapServerContextSourceFactoryBean {    val contextSourceFactoryBean = EmbeddedLdapServerContextSourceFactoryBean.fromEmbeddedLdapServer()    contextSourceFactoryBean.setPort(0)    return contextSourceFactoryBean}----======Alternatively, you can explicitly configure the LDAP `ContextSource` to connect to the supplied LDAP server..LDAP Context Source[tabs]======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]]== AuthenticationSpring 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 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:* <<servlet-authentication-ldap-bind>>* <<servlet-authentication-ldap-pwd>>[[servlet-authentication-ldap-bind]]== Using Bind Authenticationhttps://ldap.com/the-ldap-bind-operation/[Bind Authentication] 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..Bind Authentication[tabs]======Java::+[source,java,role="primary",attrs="-attributes"]----@BeanAuthenticationManager authenticationManager(BaseLdapPathContextSource contextSource) {	LdapBindAuthenticationManagerFactory factory = new LdapBindAuthenticationManagerFactory(contextSource);	factory.setUserDnPatterns("uid={0},ou=people");	return factory.createAuthenticationManager();}----XML::+[source,xml,role="secondary",attrs="-attributes"]----<ldap-authentication-provider	user-dn-pattern="uid={0},ou=people"/>----Kotlin::+[source,kotlin,role="secondary",attrs="-attributes"]----@Beanfun authenticationManager(contextSource: BaseLdapPathContextSource): AuthenticationManager {    val factory = LdapBindAuthenticationManagerFactory(contextSource)    factory.setUserDnPatterns("uid={0},ou=people")    return factory.createAuthenticationManager()}----======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:.Bind Authentication with Search Filter[tabs]======Java::+[source,java,role="primary",attrs="-attributes"]----@BeanAuthenticationManager authenticationManager(BaseLdapPathContextSource contextSource) {	LdapBindAuthenticationManagerFactory factory = new LdapBindAuthenticationManagerFactory(contextSource);	factory.setUserSearchFilter("(uid={0})");	factory.setUserSearchBase("ou=people");	return factory.createAuthenticationManager();}----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"]----@Beanfun authenticationManager(contextSource: BaseLdapPathContextSource): AuthenticationManager {    val factory = LdapBindAuthenticationManagerFactory(contextSource)    factory.setUserSearchFilter("(uid={0})")    factory.setUserSearchBase("ou=people")    return factory.createAuthenticationManager()}----======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.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.[[servlet-authentication-ldap-pwd]]== Using Password AuthenticationPassword 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[tabs]======Java::+[source,java,role="primary"]----@BeanAuthenticationManager authenticationManager(BaseLdapPathContextSource contextSource) {	LdapPasswordComparisonAuthenticationManagerFactory factory = new LdapPasswordComparisonAuthenticationManagerFactory(			contextSource, NoOpPasswordEncoder.getInstance());	factory.setUserDnPatterns("uid={0},ou=people");	return factory.createAuthenticationManager();}----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"]----@Beanfun authenticationManager(contextSource: BaseLdapPathContextSource?): AuthenticationManager? {    val factory = LdapPasswordComparisonAuthenticationManagerFactory(        contextSource, NoOpPasswordEncoder.getInstance()    )    factory.setUserDnPatterns("uid={0},ou=people")    return factory.createAuthenticationManager()}----======A more advanced configuration with some customizations can be found below..Password Compare Configuration[tabs]======Java::+[source,java,role="primary"]----@BeanAuthenticationManager authenticationManager(BaseLdapPathContextSource contextSource) {	LdapPasswordComparisonAuthenticationManagerFactory factory = new LdapPasswordComparisonAuthenticationManagerFactory(			contextSource, new BCryptPasswordEncoder());	factory.setUserDnPatterns("uid={0},ou=people");	factory.setPasswordAttribute("pwd");  // <1>	return factory.createAuthenticationManager();}----XML::+[source,xml,role="secondary",attrs="-attributes"]----<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"]----@Beanfun 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`== LdapAuthoritiesPopulatorSpring Security's `LdapAuthoritiesPopulator` is used to determine what authorites are returned for the user..LdapAuthoritiesPopulator Configuration[tabs]======Java::+[source,java,role="primary",attrs="-attributes"]----@BeanLdapAuthoritiesPopulator authorities(BaseLdapPathContextSource contextSource) {	String groupSearchBase = "";	DefaultLdapAuthoritiesPopulator authorities =		new DefaultLdapAuthoritiesPopulator(contextSource, groupSearchBase);	authorities.setGroupSearchFilter("member={0}");	return authorities;}@BeanAuthenticationManager authenticationManager(BaseLdapPathContextSource contextSource, LdapAuthoritiesPopulator authorities) {	LdapBindAuthenticationManagerFactory factory = new LdapBindAuthenticationManagerFactory(contextSource);	factory.setUserDnPatterns("uid={0},ou=people");	factory.setLdapAuthoritiesPopulator(authorities);	return factory.createAuthenticationManager();}----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"]----@Beanfun authorities(contextSource: BaseLdapPathContextSource): LdapAuthoritiesPopulator {    val groupSearchBase = ""    val authorities = DefaultLdapAuthoritiesPopulator(contextSource, groupSearchBase)    authorities.setGroupSearchFilter("member={0}")    return authorities}@Beanfun authenticationManager(    contextSource: BaseLdapPathContextSource,    authorities: LdapAuthoritiesPopulator): AuthenticationManager {    val factory = LdapBindAuthenticationManagerFactory(contextSource)    factory.setUserDnPatterns("uid={0},ou=people")    factory.setLdapAuthoritiesPopulator(authorities)    return factory.createAuthenticationManager()}----======== Active DirectoryActive 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 `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 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.This is not currently supported, but hopefully will be in a future version.].An example configuration can be seen below:.Example Active Directory Configuration[tabs]======Java::+[source,java,role="primary"]----@BeanActiveDirectoryLdapAuthenticationProvider 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"]----@Beanfun authenticationProvider(): ActiveDirectoryLdapAuthenticationProvider {    return ActiveDirectoryLdapAuthenticationProvider("example.com", "ldap://company.example.com/")}----======
 |