Аутентификация пользователя ldap с несколькими значениями суффикса/домена

Я пытаюсь пройти аутентификацию, а затем запросить дерево AD с помощью Spring Ldap Security и Spring Ldap.

Ниже приведен мой файл конфигурации -

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

    <http use-expressions="true">
        <form-login login-page="/myApp/ldap" default-target-url="/myApp/ldap/config"
            authentication-failure-url="/myApp/ldap?error=true" />
        <logout />
    </http>

    <beans:bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <beans:property name="location">
            <beans:value>classpath:/ldap.properties</beans:value>
        </beans:property>
        <beans:property name="SystemPropertiesMode">
            <beans:value>2</beans:value>
        </beans:property>
    </beans:bean>

    <beans:bean id="adAuthenticationProvider" scope="prototype"
        class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
        <!-- the domain name (may be null or empty). If no domain name is configured, it is assumed that the username will always contain the domain name. -->
        <beans:constructor-arg index="0" value="${sample.ldap.domain}" />
        <!-- an LDAP url (or multiple URLs) -->
        <beans:constructor-arg index="1" value="${sample.ldap.url}" />
        <!-- Determines whether the supplied password will be used as the credentials in the successful authentication token. -->
        <beans:property name="useAuthenticationRequestCredentials"
            value="true" />
        <!-- by setting this property to true, when the authentication fails the error codes will also be used to control the exception raised. -->
        <beans:property name="convertSubErrorCodesToExceptions"
            value="true" />
    </beans:bean>

    <authentication-manager erase-credentials="false">
        <authentication-provider ref="adAuthenticationProvider" />
    </authentication-manager>

    <beans:bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <beans:property name="location">
            <beans:value>classpath:/ldap.properties</beans:value>
        </beans:property>
        <beans:property name="SystemPropertiesMode">
            <beans:value>2</beans:value> <!-- OVERRIDE is 2 -->
        </beans:property>
    </beans:bean>

    <ldap:context-source id="contextSource" 
                         url="${sample.ldap.url}"
                         base="${sample.ldap.base}" 
                         referral="follow"
                         authentication-source-ref="authenticationSource" 
                         base-env-props-ref="baseEnvironmentProperties"/>

    <util:map id="baseEnvironmentProperties">
        <beans:entry key="com.sun.jndi.ldap.connect.timeout" value="60000" />
        <beans:entry key="java.naming.ldap.attributes.binary" value="objectGUID objectSid"/>
    </util:map>

    <beans:bean id="authenticationSource"
        class="org.springframework.security.ldap.authentication.SpringSecurityAuthenticationSource" />

    <ldap:ldap-template id="ldapTemplate"
        context-source-ref="contextSource" />

</beans:beans>

И файл свойств -

sample.ldap.url=ldap://xxx.xxx.xxx.xxx:3268
sample.ldap.base=dc=example,dc=com
sample.ldap.clean=true
sample.ldap.directory.type=AD
sample.ldap.domain=example.com

Эти настройки отлично работают для следующего входа в систему -

имя пользователя - [email protected] или пример пароля - blah

но терпит неудачу, когда я пытаюсь - имя пользователя - [email protected] или пример пароля - blah2

Оба эти входа являются действительными и были проверены при входе в систему с помощью AD Explorer.

Похоже, мне нужно обновить свою конфигурацию, чтобы поддерживать суффикс/домены UPN, так как по умолчанию работает нормально, а другие нет.

Есть ли способ, которым я могу добавить этот файл конфигурации для поддержки этой логики, поддержки аутентификации/запроса нескольких доменов?


person NewBee    schedule 02.06.2017    source источник


Ответы (2)


Причина, по которой я не могу войти в систему с настроенным суффиксом UPN, заключается в том, что ActiveDirectoryLdapAuthenticationProvider, похоже, предполагает, что суффикс UPN всегда совпадает с именем домена.

Пожалуйста, обратитесь к этому сообщению - https://github.com/spring-projects/spring-security/issues/3204

Я думаю, что должен быть лучший способ справиться с этим, или, может быть, лучшая библиотека для аутентификации.

person NewBee    schedule 05.06.2017

Чтобы объяснить решение @NewBee:

1 ActiveDirectoryLdapAuthenticationProvider:

  • Специализированный LDAP authentication provider, использующий соглашения о конфигурации Active Directory.
  • Он будет проходить аутентификацию с использованием Active Directory userPrincipalName. или sAMAccountName (или пользовательское searchFilter) в форме username@domain. Если username еще не заканчивается именем domain, userPrincipalName будет создан путем добавления сконфигурированного доменного имени к имени пользователя, указанному в authentication request. Если имя домена не настроено, предполагается, что имя пользователя всегда будет содержать имя домена.
  • Полномочия пользователя получаются из данных, содержащихся в атрибуте memberOf.

2 LDAP authentication in Spring Security:

  • Получение уникального LDAP Distinguished Name или DN из имени для входа.

    • This will often mean performing a search in the directory, unless the exact mapping of usernames to DNs is known in advance. So a user might enter his/her name when logging in, but the actual name used to authenticate to LDAP will be the full DN, such as uid=(username),ou=users,dc=springsource,dc=com.
  • Authenticating the user либо binding от имени этого пользователя, либо путем выполнения удаленной compare операции пароля пользователя с атрибутом пароля в записи каталога для DN.

  • Загрузка списка полномочий для пользователя.

Ссылку на Как для настройки нескольких суффиксов имени участника-пользователя. Кроме того, в ActiveDirectoryLdapAuthenticationProvider вы можете написать функцию для чтения нескольких суффиксов, так как библиотека адаптируема.

person King Reload    schedule 07.06.2017