Как заблокировать учетную запись пользователя LDAP в Spring Security без блокировки пользователя LDAP? - PullRequest
2 голосов
/ 24 мая 2011

Я новичок в Spring Security. В моем приложении аутентификация выполняется через Ldap. После аутентификации Ldap я хочу обрабатывать события неудачи и успеха при входе в систему. Я хочу отслеживать количество входов в базу данных для блокировки функций. кто-нибудь знает, как этого добиться?

Ответы [ 2 ]

1 голос
/ 25 мая 2011

Какая функциональность блокировки?Знаете ли вы о расширении политики паролей LDAP, которое управляет всем этим, как это?например, блокировка после нескольких неудачных входов в систему, истечение срока действия пароля / блокировка / обязательный сброс, политики качества пароля, ...

1 голос
/ 24 мая 2011

Аутентификация выполняется LDAP, но вы хотите заблокировать пользователя ldap после того, как он вошел в систему.

Если вы используете Spring 2.5, вы можете сделать свою собственную реализацию InitializingBean и проверить, является ли принципал пользователем LDAP:

public abstract class EventListener implements InitializingBean {

Log log = LogFactory.getLog(this.getClass());

EventDispatcher eventDispatcher;

// Spring will call this method after auto-
// wiring is complete.
public void afterPropertiesSet() throws Exception {
    // let us register this instance with
    // event dispatcher
    eventDispatcher.registerListener(this);
}

/**
 * Implementation of this method checks whether the given event can be
 * handled in this class. This method will be called by the event
 * dispatcher.
 * 
 * @param event
 *            the event to handle
 * @return true if the implementing subclass can handle the event
 */
public abstract boolean canHandle(Object event);

/**
 * This method is executed by the event dispatcher with the event object.
 * 
 * @param event
 *            the event to handle
 */
public abstract void handle(Object event);

public void setEventDispatcher(EventDispatcher eventDispatcher) {
    this.eventDispatcher = eventDispatcher;
}
}

А затем внедрите этот пользовательский дескриптор в loginFailureEventListener (отобразите этот слушатель в xml)

        public class LoginSuccessEventlistener extends EventListener {  

    @Override  
    public boolean canHandle(Object event) {  
        return event instanceof AuthenticationFailureBadCredentialsEvent;
    }  

    @Override  
    public void handle(Object event) {
AuthenticationFailureBadCredentialsEvent loginFailureEvent = (AuthenticationFailureBadCredentialsEvent) event;
        Object name = loginFailureEvent.getAuthentication().getPrincipal();

        if(principal instanceof org.springframework.security.userdetails.ldap.LdapUserDetailsImpl){
            out.("LDAPUser: " + user.getUsername() + " failed login");
//do you thing here
        }
    }    
}

привязка в XML:

<b:bean id="loginFailureEventListener" class="com.foo.bar.support.event.LoginFailureEventListener">
    <b:property name="eventDispatcher" ref="eventDispatcher"/>
</b:bean>

EDIT: Вы можете расширить AuthenticationProcessingFilter и переопределить метод onUnsuccessfulAuthentication:

public class CustomAuthenticationProcessingFilter extends AuthenticationProcessingFilter {
    private LoginDao loginDao;

    @Override
    protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException {
        super.onSuccessfulAuthentication(request, response, authResult);    
        request.getSession().setAttribute("wrong", -1); 
    }

    protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        super.onUnsuccessfulAuthentication(request, response, authException);
        String username = (String) authException.getAuthentication().getPrincipal();
        if(username.length() > 0){
            Login login = loginDao.read(username);
            if(login != null){
                request.getSession().setAttribute("wrong", login.getFailedLoginAttempts());
                request.getSession().setAttribute("attempts", Login.MAX_FAILED_LOGIN_ATTEMPTS);
            }else{
                request.getSession().setAttribute("wrong", 100);
            }
        }else{
            request.getSession().setAttribute("wrong", -1);
        }
    }

    public void setLoginDao(LoginDao loginDao) {
        this.loginDao = loginDao;
    }
}

Биннинг в XML:

<!-- Custom AuthenticationProcessingFilter with Callbacks -->
<authentication-manager alias="authenticationManagerAlias"/>
<b:bean id="authenticationProcessingFilter" name="authenticationProcessingFilter" class="com.foo.bat.support.event.CustomAuthenticationProcessingFilter"> 
    <b:property name="authenticationManager" ref="authenticationManagerAlias"/>
    <b:property name="authenticationFailureUrl" value="/login.do"/>
    <b:property name="filterProcessesUrl" value="/j_spring_security_check"/>
    <b:property name="defaultTargetUrl" value="/index.html"/>
    <!-- loginDao is a HibernateDao that reads logins an write wrong attempts to DB -->
    <b:property name="loginDao"><b:ref bean="loginDao"/></b:property>
    <custom-filter position="AUTHENTICATION_PROCESSING_FILTER" />          
</b:bean>

Теперь вы можете поместить этот фильтр в свой фильтр ChainProxy

Ищите здесь вдохновение http://www.harinair.com/2010/02/spring-acegi-security-account-lockout/

...