Как настроить Spring для использования внешнего сервера LDAP - PullRequest
0 голосов
/ 03 сентября 2018

Я изучаю Spring Security для LDAP-сервера, сейчас я пытаюсь сделать Spring аутентифицированным для ldap-сервера. Однако Spring всегда использует встроенный сервер ldap://127.0.0.1:33389/dc=springframework,dc=org вместо моего ldap://localhost:389/dc=localdomain,dc=local. Я пытаюсь настроить его, используя application.properties См. Ниже мою конфигурацию пружины.

WebSecurityConfig.java

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        logger.info("Loading Global Auth Configuration");
         auth
            .ldapAuthentication();

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        logger.info("Configuring HTTP Security.");
        // Configure Web Security
        http
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers("/auth/**").permitAll()
            .anyRequest().authenticated();

        // disable page caching
        http.headers().cacheControl();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        logger.info("Configuring Web Security HTTP Security.");
        // AuthenticationTokenFilter will ignore the below paths
        web
            .ignoring()
            .antMatchers(
                HttpMethod.POST,
                "/auth"
            );
    }
}

application.properties

#Ldap Info
spring.ldap.urls=ldap://localhost:389
spring.ldap.anonymous-read-only=true
spring.ldap.username=ldapadm
spring.ldap.password=root123
spring.ldap.base=ou=People,dc=localdomain,dc=local

Пробовал, используя выше application.properties, по-прежнему не работает.

application.properties

#Ldap Info
ldap.urls=ldap://localhost:389
ldap.base.dn=dc=localdomain,dc=local
ldap.username=cn=ldapadm,dc=localdomain,dc=local
ldap.password=root123
ldap.user.dn.pattern =uid={0}

Я тоже пробовал вышеуказанные свойства, все равно не работает.

2018-09-04 00:05:31.515  INFO 9948 --- [           main] s.s.l.DefaultSpringSecurityContextSource :  URL 'ldap://127.0.0.1:33389/dc=springframework,dc=org', root DN is 'dc=springframework,dc=org'
2018-09-04 00:05:31.516  INFO 9948 --- [           main] o.s.l.c.support.AbstractContextSource    : Property 'userDn' not set - anonymous context will be used for read-write operations
2018-09-04 00:05:31.523  WARN 9948 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.RuntimeException: Could not postProcess org.springframework.security.ldap.authentication.BindAuthenticator@3bc735b3 of type class org.springframework.security.ldap.authentication.BindAuthenticator
2018-09-04 00:05:31.526  INFO 9948 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]

для обеих настроек в application.properties, я всегда получаю это в моем журнале сервера

Кто-нибудь может понять это? я пытаюсь заставить его читать application.properties, но он всегда использует встроенный ldap весной

1 Ответ

0 голосов
/ 04 сентября 2018

Вы можете использовать тот же подход, что и в Аутентификация LDAP с Spring Boot

В приложении. Свойства.

ldap.urls=ldap://localhost:389/dc=localdomain,dc=local 

В вашем WebSecurityConfig

 @Value("${ldap.urls:ldap://127.0.0.1:33389/dc=springframework,dc=org}")
  private String ldapUrls;


     @Override
     public void configure(AuthenticationManagerBuilder auth) throws Exception {
     auth
     .ldapAuthentication()
     .userDnPatterns("uid={0},ou=people")
     .groupSearchBase("ou=groups")
     .contextSource()
     .url(ldapUrls)
     .and()
     .passwordCompare()
     .passwordEncoder(new LdapShaPasswordEncoder())
     .passwordAttribute("adminpassword");
     }

Обратите внимание, что фактические параметры (userDnPatterns и т. Д.), Которые могут быть изменены в соответствии с вашей конфигурацией LDAP, я только что указал, как вы можете настроить свою конфигурацию LDAP для подключения к внешнему LDAP

...