Ошибки политики паролей не генерируются с помощью LDAP Spring Security
Я довольно новичок в Spring Security с LDAP и пытаюсь пройти аутентификацию с пользователем, у которого истек срок действия пароля на сервере LDAP (FreeIPA).
Кажется, я не могу вызвать исключение с истекшим сроком действия пароля и т. Д. Элементы управления ответом политики паролей всегда возвращают ноль....
Вот мой код, возможно я что-то делаю неправильно. Как мне обрабатывать ошибки политики паролей? В настоящее время они вообще не стреляют.
<bean id="freeIpaContextSource" class="org.springframework.security.ldap.ppolicy.PasswordPolicyAwareContextSource">
<constructor-arg value="${logon.freeipa.zone.ldap.connection.url}"/>
<property name="base" value="${logon.freeipa.zone.user.dn.base}"/>
</bean>
<bean id="freeIpaLdapTemplate" class="org.springframework.security.ldap.SpringSecurityLdapTemplate">
<constructor-arg name="contextSource" ref="freeIpaContextSource"/>
</bean>
У меня есть собственный LdapAuthenticator ниже, который использует ldaptemplate для аутентификации пользователей.
@Override
public DirContextOperations authenticate(Authentication authentication) {
checkForIllegalStateDuringAuthentication(authentication);
logger.info(String.format("*** Beginning to authenticate against LDAP zone %s ***", authorizationZone.getName()));
zoneAuthenticationService.saveRequestDataInSession((UsernamePasswordAuthenticationToken) authentication, authorizationZone.getName());
CollectingAuthenticationErrorCallback errorCallback = new CollectingAuthenticationErrorCallback();
boolean isAuthenticated = false;
String userName = authentication.getName();
String password = authentication.getCredentials().toString();
String filterLookup = buildLDAPFilterLookupString(userName);
if (StringUtils.isNotBlank(password)) {
logger.info(String.format("*** Attempting authentication for user %s ***", userName));
try {
isAuthenticated = ldapTemplate.authenticate(StringUtils.EMPTY, filterLookup, password, errorCallback);
} catch (Exception exception) {
errorCallback.execute(exception);
}
}
if (!isAuthenticated) {
if (errorCallback.getError() == null) {
errorCallback.execute(new AuthenticationException(null));
}
//Any LDAP exception caught are stored inside the errorCallBack for use later to display an appropriate error.
logger.error(String.format("*** Authentication for user %s has failed. Exception has occurred while system performed LDAP authentication. ***", userName), errorCallback.getError());
throw new LdapAuthenticationException(errorCallback.getError().getMessage(), errorCallback.getError());
}
logger.info(String.format("*** Authentication for user %s has succeeded ***", userName));
return new DirContextAdapter(buildAuthenticatedDN(userName));
}
Независимо от того, что я делаю, я не могу получить никаких ошибок политики паролей для возврата. Насколько я понимаю, вам нужно установить элемент управления запросом с PasswordPolicyControl при попытке аутентификации, но я никогда не получаю никаких ответных элементов управления с сервера. Я пытался реализовать что-то вроде ниже, но не повезло ни в чем.
LdapContext context = (LdapContext)ldapTemplate.getContextSource().getContext(buildAuthenticatedDN(userName).toString(), password);
Control[] rctls = new Control[]{new PasswordPolicyControl(false)};
context.reconnect(rctls);
PasswordPolicyResponseControl ctrl = PasswordPolicyControlExtractor.extractControl(context);
//ctrl is always null
if (ctrl.isExpired()) {
throw new
PasswordPolicyException(ctrl.getErrorStatus());
}
Что я делаю неправильно? Я очень борюсь с этим, и любая помощь будет очень цениться.
1 ответ
Если ваш клиент действительно отправляет правильный ответный контроль, вы можете столкнуться с этой проблемой (открытой с 7 лет):
# 1539 [RFE] Добавить код для проверки срока действия пароля на привязке ldap
IIRC FreeIPA обеспечивает истечение срока действия пароля только во время предварительной авторизации Kerberos (kinit).