Example usage for org.springframework.security.ldap.search FilterBasedLdapUserSearch searchForUser

List of usage examples for org.springframework.security.ldap.search FilterBasedLdapUserSearch searchForUser

Introduction

In this page you can find the example usage for org.springframework.security.ldap.search FilterBasedLdapUserSearch searchForUser.

Prototype

@Override
public DirContextOperations searchForUser(String username) 

Source Link

Document

Return the LdapUserDetails containing the user's information

Usage

From source file:org.artifactory.security.ldap.LdapServiceImpl.java

public DirContextOperations searchUserInLdap(LdapTemplate ldapTemplate, String userName, LdapSetting settings) {
    if (settings.getSearch() == null) {
        return null;
    }/*  w w w.jav a2  s  . c o  m*/
    DirContextOperations contextOperations = null;
    try {
        log.debug("Searching for user {}", userName);
        List<FilterBasedLdapUserSearch> ldapUserSearches = getLdapGroupAddon()
                .getLdapUserSearches(ldapTemplate.getContextSource(), settings);
        for (FilterBasedLdapUserSearch ldapUserSearch : ldapUserSearches) {
            try {
                contextOperations = ldapUserSearch.searchForUser(userName);
            } catch (org.springframework.security.core.AuthenticationException e) {
                log.debug("Failed to retrieve groups user '{}' via LDAP: {}", userName, e.getMessage());
            }
            if (contextOperations != null) {
                break;
            }
        }
        if (contextOperations != null) {
            // Only DirContextAdapter can be used since the LDAP connection need to be released and we still need
            // read access to this LDAP context.
            if (!(contextOperations instanceof DirContextAdapter)) {
                throw new ClassCastException(
                        "Cannot use LDAP DirContext class " + contextOperations.getClass().getName()
                                + " it should be " + DirContextAdapter.class.getName());
            }
            log.debug("Found user {}, has DN: {}", userName, contextOperations.getNameInNamespace());
        }
    } catch (CommunicationException ce) {
        String message = String.format("Failed to retrieve groups for user '%s' via LDAP: communication error.",
                userName);
        log.warn(message);
    } catch (Exception e) {
        String message = "Unexpected exception in LDAP query:";
        log.debug(message, e);
        log.warn(message + "for user {} vid LDAP: {}", userName, e.getMessage());
    }
    return contextOperations;
}