Как использовать аутентификацию LDAP в корпоративной среде - PullRequest
0 голосов
/ 13 декабря 2018

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

Итак, я сделал nslookup -type=srv _ldap._tcp.MY.DOMAIN, что привело к результату:

Server: Servername.MY.DOMAIN
Address: 1.1.1.1

_ldap._tcp.MY.DOMAIN       SRV service location
      priority             = 0
      weight               = 50
      port                 = 389
      svr hostname         = a_host.MY.DOMAIN
//... a few more of these
a_host.MY.DOMAIN  internet address = 5.5.5.5

Затем я использовал этот VBS:

set objSysInfo = CreateObject("ADSystemInfo")
set objUser = GetObject("LDAP://" & objSysInfo.UserName)
wscript.echo "DN: " & objUser.distinguishedName

, который возвратил:

DN: CN=Lastname\, Firstname,OU=OU1,OU=OU2,OU=OU3,DC=MY,DC=DOMAIN

и теперь я попытался (как предложено в первом ответе) настроить приложение Spring Boot, используя этот класс для этого логина, ссылающегося на этот пост :

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .antMatcher("/secure")
            .authorizeRequests()
            .anyRequest().fullyAuthenticated()
            .and()
            .httpBasic();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(activeDirectoryLdapAuthenticationProvider());
    }

    @Bean
    public AuthenticationManager authenticationManager() {
        return new ProviderManager(Arrays.asList(activeDirectoryLdapAuthenticationProvider()));
    }
    @Bean
    public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
        ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider("MY.COMPANY", "ldap://a_host.MY.DOMAIN:389");
        provider.setConvertSubErrorCodesToExceptions(true);
        provider.setUseAuthenticationRequestCredentials(true);
        return provider;
    }
}

К сожалению, когда я запускаю приложение и вставляю учетные данные своей компании в свой Spring-Boot-Security-Login-UI, я не могу войти в приложение.Кроме того, путь /secure не доступен через http://localhost:8080/secure (в результате 404).Теперь, когда я включаю отладку для Spring-Boot-Security, я получаю следующий вывод при вставке моих учетных данных:

2018-12-17 11:47:12.793 DEBUG 13232 --- [io-8080-exec-10] o.s.security.web.FilterChainProxy        : /login at position 1 of 15 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2018-12-17 11:47:16.510 DEBUG 13232 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /login at position 1 of 15 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2018-12-17 11:47:27.462 DEBUG 13232 --- [io-8080-exec-10] o.s.security.web.FilterChainProxy        : /login at position 2 of 15 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2018-12-17 11:47:27.466 DEBUG 13232 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /login at position 2 of 15 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2018-12-17 11:47:27.466 DEBUG 13232 --- [io-8080-exec-10] w.c.HttpSessionSecurityContextRepository : HttpSession returned null object for SPRING_SECURITY_CONTEXT
2018-12-17 11:47:27.466 DEBUG 13232 --- [nio-8080-exec-9] w.c.HttpSessionSecurityContextRepository : HttpSession returned null object for SPRING_SECURITY_CONTEXT
2018-12-17 11:47:27.466 DEBUG 13232 --- [io-8080-exec-10] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@28db75a9. A new one will be created.
2018-12-17 11:47:27.466 DEBUG 13232 --- [nio-8080-exec-9] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@28db75a9. A new one will be created.
2018-12-17 11:47:27.466 DEBUG 13232 --- [io-8080-exec-10] o.s.security.web.FilterChainProxy        : /login at position 3 of 15 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2018-12-17 11:47:27.466 DEBUG 13232 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /login at position 3 of 15 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2018-12-17 11:47:27.466 DEBUG 13232 --- [io-8080-exec-10] o.s.security.web.FilterChainProxy        : /login at position 4 of 15 in additional filter chain; firing Filter: 'CsrfFilter'
2018-12-17 11:47:27.466 DEBUG 13232 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /login at position 4 of 15 in additional filter chain; firing Filter: 'CsrfFilter'
2018-12-17 11:47:27.466 DEBUG 13232 --- [io-8080-exec-10] o.s.security.web.FilterChainProxy        : /login at position 5 of 15 in additional filter chain; firing Filter: 'LogoutFilter'
2018-12-17 11:47:27.466 DEBUG 13232 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /login at position 5 of 15 in additional filter chain; firing Filter: 'LogoutFilter'
2018-12-17 11:47:27.466 DEBUG 13232 --- [io-8080-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/logout'
2018-12-17 11:47:27.466 DEBUG 13232 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/logout'
2018-12-17 11:47:27.466 DEBUG 13232 --- [io-8080-exec-10] o.s.security.web.FilterChainProxy        : /login at position 6 of 15 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2018-12-17 11:47:27.466 DEBUG 13232 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : /login at position 6 of 15 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2018-12-17 11:47:27.466 DEBUG 13232 --- [io-8080-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/login'
2018-12-17 11:47:27.466 DEBUG 13232 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/login'
2018-12-17 11:47:27.466 DEBUG 13232 --- [io-8080-exec-10] w.a.UsernamePasswordAuthenticationFilter : Request is to process authentication
2018-12-17 11:47:27.466 DEBUG 13232 --- [nio-8080-exec-9] w.a.UsernamePasswordAuthenticationFilter : Request is to process authentication
2018-12-17 11:47:27.470 DEBUG 13232 --- [io-8080-exec-10] o.s.s.authentication.ProviderManager     : Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
2018-12-17 11:47:27.470 DEBUG 13232 --- [nio-8080-exec-9] o.s.s.authentication.ProviderManager     : Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
2018-12-17 11:47:27.534 DEBUG 13232 --- [io-8080-exec-10] o.s.s.a.dao.DaoAuthenticationProvider    : User '%my_user%' not found
2018-12-17 11:47:27.534 DEBUG 13232 --- [nio-8080-exec-9] o.s.s.a.dao.DaoAuthenticationProvider    : User '%my_user%' not found
2018-12-17 11:47:27.534 DEBUG 13232 --- [io-8080-exec-10] w.a.UsernamePasswordAuthenticationFilter : Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Ung³ltige Anmeldedaten

org.springframework.security.authentication.BadCredentialsException: Ung³ltige Anmeldedaten
        at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:151) ~[spring-security-core-5.1.2.RELEASE.jar!/:5.1.2.RELEASE]
        at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174) ~[spring-security-core-5.1.2.RELEASE.jar!/:5.1.2.RELEASE]
//...
2018-12-17 11:47:27.538 DEBUG 13232 --- [nio-8080-exec-9] w.a.UsernamePasswordAuthenticationFilter : Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Ung³ltige Anmeldedaten
org.springframework.security.authentication.BadCredentialsException: Ung³ltige Anmeldedaten

, так как он не находит моего пользователя (я также пытался с именем пользователя @ DOMAIN, DOMAIN \ username...) кажется, что я либо неправильно настроил url, либо использовал неправильную форму для вставки своих данных для входа (я использовал страницу запуска при запуске приложения с Spring-Boot-Security).

ОБНОВЛЕНИЕ:

Я гарантировал, что предоставленное имя пользователя% my_user% совпадает с моим UPN, так что, похоже, это проблема конфигурации, поскольку защита при весенней загрузке говорит, что его не удается найти.

UPDATE2:

Я собираюсь обновить этот пост до самого окончательного решения, к которому мы пришли благодаря @GabrielLuci.Проблема решена:)

1 Ответ

0 голосов
/ 13 декабря 2018

В этой документации показана конфигурация для использования в .... "нормальном" каталоге LDAP (как, например, OpenLDAP).Active Directory имеет свои особенности, поэтому он не совсем ведет себя так же, как и весь остальной мир LDAP.

Spring имеет класс ActiveDirectoryLdapAuthenticationProvider только для этой цели. Этот ответ содержит пример того, как использовать его в вашем WebSecurityConfig классе:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .antMatcher("/secure")
            .authorizeRequests()
            .anyRequest().fullyAuthenticated()
            .and()
            .httpBasic();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(activeDirectoryLdapAuthenticationProvider());
    }

    @Bean
    public AuthenticationManager authenticationManager() {
        return new ProviderManager(Arrays.asList(activeDirectoryLdapAuthenticationProvider()));
    }
    @Bean
    public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
        ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider("adldap.company.com", "ldap://adldap.company.com");
        provider.setConvertSubErrorCodesToExceptions(true);
        provider.setUseAuthenticationRequestCredentials(true);
        return provider;
    }
}
...