Tags

Jul 5, 2011

Locking user account after max login attempts

Locking user account after max login attempts

@Component
     public class CustomAuthenticationEventListener implements
           ApplicationListener
     {
     public void onApplicationEvent(AbstractAuthenticationEvent event)
              throws LockedException {
           if (event instanceof AuthenticationFailureBadCredentialsEvent) {
              String username = event.getAuthentication().getName();
              UserDTO user = userService.getUserDetails(username);
              if (user != null) {
     int failedLoginAttempts =       user.getFailedLoginAttempts();
     userService.setLoginCounter(username, ++failedLoginAttempts);
     if (failedLoginAttempts == UserDTO.getMaxFailedLoginAttempts()) {
     throw new LockedException(messageSource.getMessage(
     "security.login.form.locked", null, null));
                 }
              }
           }
           if (event instanceof AuthenticationSuccessEvent) {
              String username = event.getAuthentication().getName();
              UserDTO user = userService.getUserDetails(username);
              if (user != null) {
                 userService.setLoginCounter(username, 0);
              }
           }      
        }
     } 

Retrieving ldap details using spring-ldap

  • Requirement of jar files
             Spring-ldap-core1.3.jar
  •  Define ldap properties in properties file 
# LDAP
ldap.server.url  =
ldap.rootDn      = o=stooges
ldap.userDn      = cn={0},ou=MemberGroupA,o=stooges
ldapTemplate.base=ou=MemberGroupA,o=stooges
ldapTemplate.userDn=uid=admin,ou=system
ldapTemplate.password=
  • Define ldap bean in securityContext.xml 
class="org.springframework.ldap.core.support.LdapContextSource">

  • Retrieving ldap details
            
import org.springframework.ldap.core.LdapTemplate;
      @Autowired
      private LdapTemplate ldapTemplate;
private class PersonAttributesMapper implements AttributesMapper {
            public Object mapFromAttributes(Attributes attrs)
                        throws NamingException {
                  Person userInfo = new Person ();
                  userInfo.setUsername((String) attrs.get("cn").get());
                  userInfo.setFirstName((String) attrs.get("givenname").get());
                  userInfo.setLastName((String) attrs.get("sn").get());
                  userInfo.setDisplayName((String) attrs.get("displayName").get());
                  userInfo.setApproved(true);
                  return userInfo;
            }
      }

          try {    
String dn=”login”
                  Person  userInfo = (Person) ldapTemplate.lookup(dn,
                              new PersonAttributesMapper());
            } catch (NameNotFoundException e) {
                  logger.info("Not Found in ldap " + loginId);
            }