Базовое использование Spring LDAP

Я пытаюсь понять, как работает Spring LDAP (не безопасность Spring), настроив самую простую рабочую программу, но, похоже, реальная аутентификация не работает.

Это ошибка, которую я получаю:

Exception in thread "main" java.lang.NullPointerException
    at org.springframework.ldap.core.support.AbstractContextSource.getReadOnlyContext(AbstractContextSource.java:125)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:287)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:237)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:588)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:546)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:401)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:421)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:441)

Код, который выполняется в методе, вызывающем исключение:

return getContext(authenticationSource.getPrincipal(),
                  authenticationSource.getCredentials());

Итак, похоже, мне нужно настроить источник аутентификации в контексте приложения? Я действительно потерян.

Вот мой код:

package se.test.connector.ldap;

import java.util.List;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.DistinguishedName;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.ldap.filter.EqualsFilter;

public class LdapTest {

    public static void main(String[] args) {
        LdapContextSource ctxSrc = new LdapContextSource();
        ctxSrc.setUrl("ldap://<ldapUrl>:389");
        ctxSrc.setBase("DC=bar,DC=test,DC=foo");
        ctxSrc.setUserDn("<username>@bar.test.foo");
        ctxSrc.setPassword("<password>");

        LdapTemplate tmpl = new LdapTemplate(ctxSrc);

        PersonDao dao = new PersonDao(tmpl);
        dao.getAllPersonNames();
    }

    public static class PersonDao {

        private LdapTemplate ldapTemplate;

        public PersonDao(LdapTemplate ldapTemplate) {
            this.ldapTemplate = ldapTemplate;
        }

        public void setLdapTemplate(LdapTemplate ldapTemplate) {
            this.ldapTemplate = ldapTemplate;
        }

        public List getAllPersonNames() {
            EqualsFilter filter = new EqualsFilter("objectclass", "person");
            return ldapTemplate.search(DistinguishedName.EMPTY_PATH,
                    filter.encode(),
                    new AttributesMapper() {

                        public Object mapFromAttributes(Attributes attrs) throws NamingException {
                            return attrs.get("cn").get();
                        }
                    });
        }
    }
}

person damd    schedule 06.09.2012    source источник


Ответы (2)


Это выглядит правильно, на поверхности. Во-первых, ваш userDn на самом деле не является правильным отличительным именем. Он должен быть в формате "CN=<...>, DC=bar, DC=test, DC=foo". Поскольку вы не даете подробностей о том, какой сервер LDAP вы используете или как выглядит ваша структура каталогов (структура OU и т. д.), трудно быть более точным.

person pap    schedule 06.09.2012
comment
Кроме того, я никогда не пытался отдельно установить базу пользователей и uid. Попробуйте не устанавливать базу и установить UserDN с полным DN. - person Samuel EUSTACHI; 10.09.2012

У меня была очень похожая проблема - тоже с NullPointerException.

Что решило мою проблему, так это вызов afterPropertiesSet():

// ...

LdapContextSource ctxSrc = new LdapContextSource();
ctxSrc.setUrl("ldap://<ldapUrl>:389");
ctxSrc.setBase("DC=bar,DC=test,DC=foo");
ctxSrc.setUserDn("<username>@bar.test.foo");
ctxSrc.setPassword("<password>");

ctxSrc.afterPropertiesSet(); /* ! */

LdapTemplate tmpl = new LdapTemplate(ctxSrc);

// ...
person ollo    schedule 05.12.2012
comment
Вызов afterPropertiesSet() решил мою проблему, в то время как у меня было такое же исключение нулевого указателя - person waterazu; 22.11.2016
comment
это реальный ответ, если вы получили NPE, вызванный authenticationSource == null - person Kooki; 13.03.2017