Using credentials for Spring LDAP autentification

71 views Asked by At

There is an LDAP-server in the local network. I'm trying to autentificate users in a Spring app with Spring LDAP. There are many users and everyone should have possibility to enter their credentials in the Spring app, with which I could autentificate them to the LDAP-server.

Test code snippet for autentification:

fun test() {
    val contextSource = LdapContextSource()
    contextSource.setUrl("ldap://server.com:389/")
    contextSource.setBase("DC=server,DC=com")
    contextSource.userDn = "[email protected]"
    contextSource.password = "supersecretpassword"
    contextSource.afterPropertiesSet()

    val ldapTemplate = LdapTemplate(contextSource)
    ldapTemplate.afterPropertiesSet()

    val query = query().where("userprincipalname").`is`("[email protected]")
    ldapTemplate.authenticate(query,  "supersecretpassword")
}

This is a working code, user is autentificated. But here are some points I don't understand:

  1. For what it is necessary to specify the login and password of the user in LdapContextSource, and then in LdapTemplate when executing autentification? It is logical, after all, if I know the user credentials, I enter them it one place. But if I don't specify the credentials in LdapContextSource, then when executing ldapTemplate.authenticate(..) I'll get an exception. Moreover, an exception won't be thrown either when creating LdapContextSource either LdapTemplate. I only have an assumption that credentials in LdapContextSource have to be with admin rights. But for what? Knowledge of your username and password should be enough for autentification.
  2. The second problem is a consequence of the first. Above, I wrote a code snippet with creating instances of the LdapContextSource and LdapTemplate. But a good point is to create beans of these classes. But I can't create beans of these classes because there are a lot of users and, accordingly, their credentials. I have to create instances of LdapContextSource and LdapTemplate every time a user logs in.

By the way, you can authenticate a user without specifying his credentials in LdapContextSource:

fun test() {
    val contextSource = LdapContextSource()
    contextSource.setUrl("ldap://server.com:389/")
    contextSource.afterPropertiesSet()
    val dirContext = contextSource.getContext("[email protected]", "supersecretpassword")
}

But in this case you won't get a list of user attributes, only a list of domain attributes.

Library versions:

  • org.springframework.ldap:spring-ldap-core:2.2.0.RELEASE
  • org.springframework.boot:spring-boot-starter-data-ldap:2.2.0.RELEASE
0

There are 0 answers