Spring Security LDAP и MD5 хэшированные пароли - PullRequest
2 голосов
/ 12 марта 2012

Я пытаюсь получить доступ к своему проекту с использованием LDAP. Он запрашивает имя пользователя и пароль успешно, но при вводе правильных учетных данных в нем снова появляется всплывающее окно (кажется, учетные данные неверны, но это не так).

Вот мой security-context.xml:

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

  <ldap-server url="ldap://${ldap.host}:${ldap.port}/${ldap.root}" manager-dn="${ldap.manager.dn}" manager-password="${ldap.manager.password}" />

  <authentication-manager>
    <ldap-authentication-provider group-search-base="${ldap.group.search.base}" user-search-filter="(uid={0})" user-search-base="${ldap.user.search.base}" />
  </authentication-manager>

  <http use-expressions="true">
    <intercept-url pattern="/**" />
    <http-basic />
  </http>

</beans:beans>

Пароли хранятся в виде хеша {MD5} ... И я использую jsr 250 api.

EDIT: @TobyHobson это приводит к org.xml.sax.SAXParseException; lineNumber: 14; columnNumber: 38; cvc-complex-type.2.4.a: Invalid content was found starting with element 'password-encoder'. One of '{"http://www.springframework.org/schema/security":password-compare}' is expected.

EDIT2: @TobyHobson, помещающий password-compare вокруг password-encoder, кажется, компилируется, но все равно отклоняет мои правильные учетные данные.

EDIT3: Вот необходимые журналы:

DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'sessionFactory'
DEBUG: org.springframework.security.web.FilterChainProxy - /licenses/index.html at position 1 of 8 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
DEBUG: org.springframework.security.web.context.HttpSessionSecurityContextRepository - HttpSession returned null object for SPRING_SECURITY_CONTEXT
DEBUG: org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@397af435. A new one will be created.
DEBUG: org.springframework.security.web.FilterChainProxy - /licenses/index.html at position 2 of 8 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
DEBUG: org.springframework.security.web.authentication.www.BasicAuthenticationFilter - Basic Authentication Authorization header found for user 'demo_admin'
DEBUG: org.springframework.security.authentication.ProviderManager - Authentication attempt using org.springframework.security.ldap.authentication.LdapAuthenticationProvider
DEBUG: org.springframework.security.ldap.authentication.LdapAuthenticationProvider - Processing authentication request for user: demo_admin
DEBUG: org.springframework.security.ldap.search.FilterBasedLdapUserSearch - Searching for user 'demo_admin', with user search [ searchFilter: '(uid={0})', searchBase: 'ou=people', scope: subtree, searchTimeLimit: 0, derefLinkFlag: false ]
DEBUG: org.springframework.security.ldap.SpringSecurityLdapTemplate - Searching for entry under DN 'dc=ubuntu,dc=local', base = 'ou=people', filter = '(uid={0})'
DEBUG: org.springframework.security.ldap.SpringSecurityLdapTemplate - Found DN: uid=demo_admin,ou=people
DEBUG: org.springframework.security.ldap.authentication.PasswordComparisonAuthenticator - Performing LDAP compare of password attribute 'userPassword' for user 'uid=demo_admin,ou=people'
DEBUG: org.springframework.security.web.authentication.www.BasicAuthenticationFilter - Authentication request for failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials
DEBUG: org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
DEBUG: org.springframework.security.web.context.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed

РЕДАКТИРОВАТЬ 4: Я думаю, что это имеет какое-то отношение к API jsr 250 и групп / ролей. Вот мой ldif:

dn: ou=people,dc=ubuntu,dc=local
objectClass: organizationalUnit
ou: people

dn: uid=demo_admin,ou=people,dc=ubuntu,dc=local
userPassword: {MD5}fe01ce2a7fbac8fafaed7c982a04e229
objectClass: posixAccount
objectClass: account
homeDirectory: null
uid: demo_admin
uidNumber: 1001
gidNumber: 1000
cn: Demo Admin

dn: uid=demo_manager,ou=people,dc=ubuntu,dc=local
userPassword: {MD5}fe01ce2a7fbac8fafaed7c982a04e229
objectClass: posixAccount
objectClass: account
homeDirectory: null
uid: demo_manager
uidNumber: 2001
gidNumber: 2000
cn: Demo Manager

dn: uid=demo_viewer,ou=people,dc=ubuntu,dc=local
userPassword: {MD5}fe01ce2a7fbac8fafaed7c982a04e229
objectClass: posixAccount
objectClass: account
homeDirectory: null
uid: demo_viewer
uidNumber: 3001
gidNumber: 3000
cn: Demo Viewer

dn: ou=groups,dc=ubuntu,dc=local
objectClass: organizationalUnit
ou: groups

dn: cn=Admins,ou=groups,dc=ubuntu,dc=local
objectClass: posixGroup
cn: Admins
gidNumber: 1000

dn: cn=Managers,ou=groups,dc=ubuntu,dc=local
objectClass: posixGroup
cn: Managers
gidNumber: 2000

dn: cn=Viewers,ou=groups,dc=ubuntu,dc=local
objectClass: posixGroup
cn: Viewers
gidNumber: 3000

Я использовал @RolesAllowed({ Role.ROLE_ADMIN, Role.ROLE_MANAGER, Role.ROLE_VIEWER }) в своем контроллере, и это мой класс ролей:

public abstract class Role
{
  public static final String ROLE_ADMIN = "Admins";
  public static final String ROLE_MANAGER = "Managers";
  public static final String ROLE_VIEWER = "Viewers";
}

Ответы [ 3 ]

1 голос
/ 06 июня 2013

Нет необходимости определять хеширование в файле конфигурации безопасности Spring, технику хеширования будет обрабатывать сам ldap. Единственное, что вам нужно сделать, это сохранить пароль MD5 в ldap следующим образом ...

              Attributes attrs = new BasicAttributes();
      BasicAttribute ocattr = new BasicAttribute("objectclass");
      ocattr.add("top");
      ocattr.add("person");
      ocattr.add("inetorgperson");
      ocattr.add("organizationalperson");
      attrs.put(ocattr);
      attrs.put("sn",user.getName());
      attrs.put("userPassword","{MD5}"+user.getPassword());
1 голос
/ 12 марта 2012

Вам необходимо добавить кодировщик пароля к вашему провайдеру аутентификации, чтобы сказать Spring, чтобы хэшировать пароль перед привязкой в ​​LDAP.например,

<authentication-manager>
  <ldap-authentication-provider group-search-base="${ldap.group.search.base}" user-search-filter="(uid={0})" user-search-base="${ldap.user.search.base}">
    <password-encoder hash="md5"/>
  </ldap-authentication-provider>
</authentication-manager>

Если вы используете соль, вам также необходимо включить ее, например,

<password-encoder hash="md5">
  <salt-source user-property="username"/>
</password-encoder>
0 голосов
/ 13 марта 2012

Схема кодирования пароля не имеет значения при использовании аутентификации bind, поскольку проверка пароля выполняется в каталоге, а не в коде Spring Security, поэтому Spring Security не нужно хешировать пароль или иметь какие-либо знания о том, как он хранится.Оно будет отправлено в виде открытого текста в каталог, поэтому вам следует использовать соединение ldaps, если вас это беспокоит.

Если вы проходите аутентификацию с использованием операции сравнения LDAP, то вам придется отправить идентичную копиюполя пароля к каталогу.Это подвержено ошибкам, так как это зависит от правильности регистра и т. Д. Также в настоящее время отсутствует поддержка хешей {MD5}, хотя есть LdapShaPasswordEncoder, который обрабатывает {SHA} и {SSHA}.

Скорее всего, ваша установка завершается ошибкой по какой-то другой причине, что должно быть ясно из более детального изучения журналов отладки и журнала вашего сервера LDAP.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...