Как использовать Apache DS с Apache Camel, Spring Security в качестве встроенного сервера LDAP, предварительно заполненного из LDIF?

Я пытаюсь создать интеграционный тест с Apache Camel LDAP и Spring Security. К сожалению, встроенный Apache DS выдает следующую ошибку, когда я пытаюсь предварительно заполнить его LDIF (загруженным из руководство пользователя ApacheDS) при запуске:

Сообщение об ошибке при запуске

2013-06-27 09:51:32,002 [main           ] INFO  AbstractContextLoader          - Detected default resource location "classpath:/eu/hermes/esb/gateway/LdapRouteTest-context.xml" for test class [eu.hermes.esb.gateway.LdapRouteTest].
2013-06-27 09:51:32,003 [main           ] INFO  DelegatingSmartContextLoader   - GenericXmlContextLoader detected default locations for context configuration [ContextConfigurationAttributes@16ba8602 declaringClass = 'eu.hermes.esb.gateway.LdapRouteTest', locations = '{classpath:/eu/hermes/esb/gateway/LdapRouteTest-context.xml}', classes = '{}', inheritLocations = true, contextLoaderClass = 'org.springframework.test.context.ContextLoader'].
2013-06-27 09:51:32,003 [main           ] INFO  AnnotationConfigContextLoader  - Could not detect default configuration classes for test class [eu.hermes.esb.gateway.LdapRouteTest]: LdapRouteTest does not declare any static, non-private, non-final, inner classes annotated with @Configuration.
2013-06-27 09:51:32,005 [main           ] INFO  TestContextManager             - @TestExecutionListeners is not present for class [class eu.hermes.esb.gateway.LdapRouteTest]: using defaults.
2013-06-27 09:51:32,097 [main           ] INFO  XmlBeanDefinitionReader        - Loading XML bean definitions from class path resource [eu/hermes/esb/gateway/LdapRouteTest-context.xml]
2013-06-27 09:51:32,356 [main           ] INFO  SpringSecurityCoreVersion      - You are running with Spring Security Core 3.1.4.RELEASE
2013-06-27 09:51:32,357 [main           ] INFO  SecurityNamespaceHandler       - Spring Security 'config' module version is 3.1.4.RELEASE
2013-06-27 09:51:32,372 [main           ] INFO  LdapServerBeanDefinitionParser - Embedded LDAP server bean definition created for URL: ldap://127.0.0.1:389/dc=example,dc=com
2013-06-27 09:51:32,408 [main           ] DEBUG CamelNamespaceHandler          - Using org.apache.camel.spring.CamelContextFactoryBean as CamelContextBeanDefinitionParser
2013-06-27 09:51:32,975 [main           ] DEBUG CamelNamespaceHandler          - Registered default: org.apache.camel.spring.CamelProducerTemplateFactoryBean with id: template on camel context: camel-1
2013-06-27 09:51:32,975 [main           ] DEBUG CamelNamespaceHandler          - Registered default: org.apache.camel.spring.CamelConsumerTemplateFactoryBean with id: consumerTemplate on camel context: camel-1
2013-06-27 09:51:32,984 [main           ] INFO  GenericApplicationContext      - Refreshing org.springframework.context.support.GenericApplicationContext@7f56b6b9: startup date [Thu Jun 27 09:51:32 CEST 2013]; root of context hierarchy
2013-06-27 09:51:33,059 [main           ] INFO  DefaultListableBeanFactory     - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@7619ed7e: defining beans [org.springframework.security.apacheDirectoryServerContainer,org.springframework.security.securityContextSource,ldapserver,template,consumerTemplate,camel-1:beanPostProcessor,camel-1,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
2013-06-27 09:51:33,319 [main           ] INFO  ApacheDSContainer              - Setting working directory for LDAP_PROVIDER: C:\Users\MYUSERNAME\AppData\Local\Temp\apacheds-spring-security-8794490705744
2013-06-27 09:51:33,382 [main           ] INFO  ApacheDSContainer              - Starting directory server...
2013-06-27 09:51:33,382 [main           ] WARN  DefaultDirectoryService        - ApacheDS shutdown hook has NOT been registered with the runtime.  This default setting for standalone operation has been overriden.
2013-06-27 09:51:34,002 [main           ] ERROR DefaultAttributeTypeRegistry   - attributeType w/ OID 2.5.4.16 not registered!
2013-06-27 09:51:34,451 [main           ] INFO  TlsKeyGenerator                - Keys and self signed certificate successfully generated.
2013-06-27 09:51:34,615 [main           ] INFO  LdapServer                     - Successful bind of an LDAP Service (389) is completed.
2013-06-27 09:51:34,615 [main           ] INFO  LdapServer                     - Ldap service started.
2013-06-27 09:51:34,624 [main           ] INFO  ApacheDSContainer              - Loading LDIF file: D:\projekte\ESB\esb-webservice-gateway\target\test-classes\apache-ds-tutorial.ldif
2013-06-27 09:51:34,632 [main           ] INFO  LdifFileLoader                 - Could not create entry ClientEntry
    dn: ou=people,o=sevenSeas
    objectclass: organizationalUnit
    objectclass: top
    ou: people
    description: Contains entries which describe persons (seamen)

org.apache.directory.shared.ldap.exception.LdapNameNotFoundException:  Cannot find a partition for 2.5.4.11=people,2.5.4.10=sevenseas

Мой XML контекст верблюда

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:camel="http://camel.apache.org/schema/spring"
    xmlns:cxf="http://camel.apache.org/schema/cxf"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://camel.apache.org/schema/spring
       http://camel.apache.org/schema/spring/camel-spring.xsd
       http://www.springframework.org/schema/security
       http://www.springframework.org/schema/security/spring-security.xsd
       http://camel.apache.org/schema/cxf
       http://camel.apache.org/schema/cxf/camel-cxf.xsd">

    <security:ldap-server root="dc=example,dc=com" port="389" ldif="classpath:apache-ds-tutorial.ldif" />

    <!-- ldap settings -->
    <bean id="ldapserver" class="javax.naming.directory.InitialDirContext" scope="prototype">
        <constructor-arg>
            <props>
                <prop key="java.naming.factory.initial">com.sun.jndi.ldap.LdapCtxFactory</prop>
                <prop key="java.naming.provider.url">ldap://127.0.0.1:389</prop>
                <prop key="java.naming.security.authentication">none</prop>
                <!--
                <prop key="java.naming.referral">ignore</prop>
                <prop key="java.naming.security.principal">admin</prop>
                <prop key="java.naming.security.credentials">admin</prop>
                -->
            </props>
        </constructor-arg>
    </bean>

    <!-- this is the Camel route which proxies the real web service and forwards
        SOAP requests to it -->
    <camelContext xmlns="http://camel.apache.org/schema/spring">
        <route>
            <from uri="direct:start" />
            <to uri="bean:ldapserver?method=doLookup('${body}')" />
            <to uri="mock:result" />
        </route>
    </camelContext>
</beans>

Мой вопрос

Должен ли я автоматически создавать раздел? Если да, как мне настроить это с помощью <security:ldap-server ... />? Нет атрибута, который выглядит правильно, поэтому я думаю, что мне нужно сделать некоторые @Before в моем классе junit, содержащем тест.

Обновление 1: мне удалось продвинуться дальше, указав корневой DN из моего файла LDIF в конфигурации безопасности Spring:

<security:ldap-server root="ou=people,o=sevenSeas" port="389" ldif="classpath:apache-ds-tutorial.ldif" />

После этого я удалил из файла LDIF все, что не связано с ou=people,o=sevenSeas. Теперь я вижу следующие сообщения журнала:

2013-06-27 11:04:30,193 [main           ] INFO  ApacheDSContainer              - Starting directory server...
2013-06-27 11:04:30,193 [main           ] WARN  DefaultDirectoryService        - ApacheDS shutdown hook has NOT been registered with the runtime.  This default setting for standalone operation has been overriden.
2013-06-27 11:04:30,816 [main           ] ERROR DefaultAttributeTypeRegistry   - attributeType w/ OID 2.5.4.16 not registered!
2013-06-27 11:04:31,252 [main           ] INFO  TlsKeyGenerator                - Keys and self signed certificate successfully generated.
2013-06-27 11:04:31,414 [main           ] INFO  LdapServer                     - Successful bind of an LDAP Service (389) is completed.
2013-06-27 11:04:31,414 [main           ] INFO  LdapServer                     - Ldap service started.
2013-06-27 11:04:31,417 [main           ] ERROR ApacheDSContainer              - Failed to create dc entry
java.lang.IllegalArgumentException: [Assertion failed] - this expression must be true
    at org.springframework.util.Assert.isTrue(Assert.java:65)
    at org.springframework.util.Assert.isTrue(Assert.java:77)
    at org.springframework.security.ldap.server.ApacheDSContainer.start(ApacheDSContainer.java:189)
    at org.springframework.security.ldap.server.ApacheDSContainer.afterPropertiesSet(ApacheDSContainer.java:130)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:472)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:103)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:1)
    at org.springframework.test.context.support.DelegatingSmartContextLoader.loadContext(DelegatingSmartContextLoader.java:228)
    at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:124)
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:148)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:290)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
2013-06-27 11:04:31,420 [main           ] INFO  ApacheDSContainer              - Loading LDIF file: D:\projekte\ESB\esb-webservice-gateway\target\test-classes\apache-ds-tutorial.ldif
2013-06-27 11:04:31,436 [main           ] INFO  LdifFileLoader                 - Created null.
2013-06-27 11:04:31,443 [main           ] INFO  LdifFileLoader                 - Created null.
2013-06-27 11:04:31,448 [main           ] INFO  LdifFileLoader                 - Created null.
2013-06-27 11:04:31,454 [main           ] INFO  LdifFileLoader                 - Created null.
2013-06-27 11:04:31,460 [main           ] INFO  LdifFileLoader                 - Created null.
2013-06-27 11:04:31,473 [main           ] INFO  ultSpringSecurityContextSource -  URL 'ldap://127.0.0.1:389/ou=people,o=sevenSeas', root DN is 'ou=people,o=sevenSeas'

Версии

  • Верблюд 2.11.0
  • Весна 3.1.4.РЕЛИЗ

ОБНОВЛЕНИЕ Я создал список с моими файлами для справки по адресу https://gist.github.com/MoriTanosuke/5882934


person cringe    schedule 27.06.2013    source источник


Ответы (2)


Корневая запись во встроенном сервере ограничена «доменом», поэтому вы ограничены DN, которые заканчиваются на «dc=blah,dc=blahblah».

вы можете рассмотреть возможность использования Тесты LDAP от Spring Security в качестве отправной точки, поскольку они уже запущены и работают.

person Shaun the Sheep    schedule 27.06.2013

Во-первых, у моего LdapRouteTest-context.xml была очень глупая ошибка. Мое определение маршрута было

<camelContext xmlns="http://camel.apache.org/schema/spring">
    <route>
        <from uri="direct:start" />
        <to uri="bean:ldapserver?method=doLookup('${body}')" />
        <to uri="mock:result" />
    </route>
</camelContext>

и я ссылался на bean-компонент ldapserver как на простой bean-компонент. Правильный способ использования camel-ldap таков:

<camelContext xmlns="http://camel.apache.org/schema/spring">
    <route>
        <from uri="direct:start" />
        <to uri="ldap:ldapserver?base=ou=people,o=sevenseas" />
        <to uri="mock:result" />
    </route>
</camelContext>

Мне пришлось использовать параметр base=ou=people,o=sevenseas, иначе я не получил бы никаких результатов поиска. Может быть, это потому, что я еще не разбираюсь в поисковых фильтрах LDAP, или, может быть, вы должны использовать camel-ldap именно так. Во всяком случае, теперь я могу использовать встроенный сервер LDAP с файлом LDIF для своих интеграционных тестов.

Я обновил суть всеми своими файлами по адресу https://gist.github.com/MoriTanosuke/5882934 для последующих ссылок.

person cringe    schedule 28.06.2013