Example usage for org.springframework.security.ldap SpringSecurityLdapTemplate SpringSecurityLdapTemplate

List of usage examples for org.springframework.security.ldap SpringSecurityLdapTemplate SpringSecurityLdapTemplate

Introduction

In this page you can find the example usage for org.springframework.security.ldap SpringSecurityLdapTemplate SpringSecurityLdapTemplate.

Prototype

public SpringSecurityLdapTemplate(ContextSource contextSource) 

Source Link

Usage

From source file:com.netflix.spinnaker.fiat.config.LdapConfig.java

@Bean
SpringSecurityLdapTemplate springSecurityLdapTemplate() throws Exception {
    DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(configProps.url);
    contextSource.setUserDn(configProps.managerDn);
    contextSource.setPassword(configProps.managerPassword);
    contextSource.afterPropertiesSet();/*w  w  w. ja v a2s .co m*/

    return new SpringSecurityLdapTemplate(contextSource);
}

From source file:no.dusken.common.plugin.ldapplugin.auth.DuskenLdapAuthoritiesPopulator.java

/**
 * This method should be overridden if required to obtain any additional
 * roles for the given user (on top of those obtained from the standard
 * search implemented by this class)./*from   www.j  av a 2 s  . c  om*/
 *
 * @param user     the context representing the user who's roles are required
 * @param username the username representing the user who's roles are required
 * @return the extra roles which will be merged with those returned by the group search
 */
@Override
protected Set<GrantedAuthority> getAdditionalRoles(DirContextOperations user, String username) {

    // this is like "employeeNumber: 396"
    String employeeNumberString = user.getStringAttribute("employeeNumber");
    // get the last number
    employeeNumberString = employeeNumberString.replaceFirst("employeeNumber: ", "");
    Long employeeNumber = Long.parseLong(employeeNumberString);

    // I need this:
    SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(getContextSource());

    String groupSearchFilter = "memberID=" + employeeNumber;

    //noinspection unchecked
    Set<String> userRoles = ldapTemplate.searchForSingleAttributeValues(getGroupSearchBase(), groupSearchFilter,
            new String[] { user.getDn().toString(), username }, "roleName");
    Set<GrantedAuthority> set = new HashSet<GrantedAuthority>();

    for (String role : userRoles) {
        set.add(new GrantedAuthorityImpl("ROLE_" + role.toUpperCase().replaceAll(" ", "_")));
    }

    return set;
}

From source file:it.geosolutions.geostore.services.rest.security.GeoStoreLdapAuthoritiesPopulator.java

/**
 * @param contextSource/*from w  w  w .  j  a  v  a 2 s .co m*/
 * @param groupSearchBase
 */
public GeoStoreLdapAuthoritiesPopulator(ContextSource contextSource, String groupSearchBase,
        String roleSearchBase) {
    super(contextSource, groupSearchBase);

    Assert.notNull(contextSource, "contextSource must not be null");
    ldapTemplate = new SpringSecurityLdapTemplate(contextSource);
    ldapTemplate.setSearchControls(searchControls);

    this.groupSearchBase = groupSearchBase;

    if (groupSearchBase == null) {
        logger.info("groupSearchBase is null. No group search will be performed.");
    } else if (groupSearchBase.length() == 0) {
        logger.info("groupSearchBase is empty. Searches will be performed from the context source base");
    }

    this.roleSearchBase = roleSearchBase;

    if (roleSearchBase == null) {
        logger.info("roleSearchBase is null. No group search will be performed.");
    } else if (roleSearchBase.length() == 0) {
        logger.info("roleSearchBase is empty. Searches will be performed from the context source base");
    }
}

From source file:com.orangeleap.common.security.OrangeLeapLdapUserSearch.java

/**
 * Return the LdapUserDetails containing the user's information
 *
 * @param username the username to search for.
 * @return An LdapUserDetails object containing the details of the located user's directory entry
 * @throws UsernameNotFoundException if no matching entry is found.
 *//*from   w w w.j a  v  a  2  s . c om*/
public DirContextOperations searchForUser(String username) {
    SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(contextSource);

    template.setSearchControls(searchControls);

    try {

        String[] filterArgs;
        String aSearchBase;

        if (username.indexOf("@") > -1) {
            String[] split = username.split("@");
            filterArgs = new String[] { split[0] };
            aSearchBase = "o=" + split[1];
        } else {
            filterArgs = new String[] { username };
            aSearchBase = searchBase;
        }

        return template.searchForSingleEntry(aSearchBase, searchFilter, filterArgs);

    } catch (IncorrectResultSizeDataAccessException notFound) {
        if (notFound.getActualSize() == 0) {
            throw new UsernameNotFoundException("User " + username + " not found in directory.", username);
        }
        // Search should never return multiple results if properly configured, so just rethrow
        throw notFound;
    }
}

From source file:com.orangeleap.common.security.OrangeLeapLdapAuthoritiesPopulator.java

/**
 * Constructor for group search scenarios. <tt>userRoleAttributes</tt> may still be
 * set as a property.//from  w  w  w .  ja va  2  s  . c o m
 *
 * @param contextSource supplies the contexts used to search for user roles.
 * @param groupSearchBase          if this is an empty string the search will be performed from the root DN of the
 *                                 context factory.
 */
public OrangeLeapLdapAuthoritiesPopulator(ContextSource contextSource, String groupSearchBase) {
    Assert.notNull(contextSource, "contextSource must not be null");
    ldapTemplate = new SpringSecurityLdapTemplate(contextSource);
    ldapTemplate.setSearchControls(searchControls);
    setGroupSearchBase(groupSearchBase);
}

From source file:com.orangeleap.common.security.OrangeLeapBindAuthenticator.java

private DirContextOperations bindWithDn(String userDn, String username, String password) {
    SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(new BindWithSpecificDnContextSource(
            (SpringSecurityContextSource) getContextSource(), userDn, password));

    try {/*from  ww w  . ja va 2 s  .com*/
        return template.retrieveEntry(userDn, getUserAttributes());

    } catch (BadCredentialsException e) {
        // This will be thrown if an invalid user name is used and the method may
        // be called multiple times to try different names, so we trap the exception
        // unless a subclass wishes to implement more specialized behaviour.
        handleBindException(userDn, username, e.getCause());
    }

    return null;
}

From source file:com.orangeleap.common.security.OrangeLeapLdapUserSearch.java

/**
 * Return the LdapUserDetails containing the user's information
 *
 * @param username the username to search for.
 * @return An LdapUserDetails object containing the details of the located user's directory entry
 * @throws UsernameNotFoundException if no matching entry is found.
 *//*from   www .  ja  v a 2  s.com*/
public DirContextOperations searchForUser(String username, String site) {
    SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(contextSource);

    template.setSearchControls(searchControls);

    try {
        String searchBase = "o=" + site;
        return template.searchForSingleEntry(searchBase, searchFilter, new String[] { username });

    } catch (IncorrectResultSizeDataAccessException notFound) {
        if (notFound.getActualSize() == 0) {
            throw new UsernameNotFoundException("User " + username + " not found in directory.", username);
        }
        // Search should never return multiple results if properly configured, so just rethrow
        throw notFound;
    }
}

From source file:org.apache.ranger.service.PasswordComparisonAuthenticator.java

public DirContextOperations authenticate(final Authentication authentication) {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            "Can only process UsernamePasswordAuthenticationToken objects");
    // locate the user and check the password

    DirContextOperations user = null;//from   w w  w. jav  a2s .c  o m
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    Iterator dns = getUserDns(username).iterator();

    SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(getContextSource());

    while (dns.hasNext() && user == null) {
        final String userDn = (String) dns.next();

        try {
            user = ldapTemplate.retrieveEntry(userDn, getUserAttributes());
        } catch (NameNotFoundException ignore) {
        }
    }

    if (user == null && getUserSearch() != null) {
        user = getUserSearch().searchForUser(username);
    }

    if (user == null) {
        throw new UsernameNotFoundException("User not found: " + username, username);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Performing LDAP compare of password attribute '" + passwordAttributeName + "' for user '"
                + user.getDn() + "'");
    }

    String encodedPassword = passwordEncoder.encodePassword(password, null);
    byte[] passwordBytes = encodedPassword.getBytes();

    if (!ldapTemplate.compare(user.getDn().toString(), passwordAttributeName, passwordBytes)) {
        throw new BadCredentialsException(
                messages.getMessage("PasswordComparisonAuthenticator.badCredentials", "Bad credentials"));
    }

    return user;
}

From source file:org.cloudfoundry.identity.uaa.ldap.PasswordComparisonAuthenticator.java

@Override
public DirContextOperations authenticate(Authentication authentication) {
    DirContextOperations user = null;/*from   w w w  .  j  a va2s  .  co m*/
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(getContextSource());

    for (String userDn : getUserDns(username)) {
        try {
            user = ldapTemplate.retrieveEntry(userDn, getUserAttributes());
        } catch (NameNotFoundException ignore) {
        }
        if (user != null) {
            break;
        }
    }

    if (user == null && getUserSearch() != null) {
        user = getUserSearch().searchForUser(username);
    }

    if (user == null) {
        throw new UsernameNotFoundException("User not found: " + username, username);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Performing LDAP compare of password attribute '" + passwordAttributeName + "' for user '"
                + user.getDn() + "'");
    }

    if (isLocalCompare()) {
        localCompareAuthenticate(user, password);
    } else {
        String encodedPassword = passwordEncoder.encodePassword(password, null);
        byte[] passwordBytes = Utf8.encode(encodedPassword);
        searchAuthenticate(user, passwordBytes, ldapTemplate);
    }

    return user;

}

From source file:org.cloudfoundry.identity.uaa.provider.ldap.PasswordComparisonAuthenticator.java

@Override
public DirContextOperations authenticate(Authentication authentication) {
    DirContextOperations user = null;/*from   w w  w . j a  v a 2  s .  co m*/
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(getContextSource());

    for (String userDn : getUserDns(username)) {
        try {
            user = ldapTemplate.retrieveEntry(userDn, getUserAttributes());
        } catch (NameNotFoundException ignore) {
        }
        if (user != null) {
            break;
        }
    }

    if (user == null && getUserSearch() != null) {
        user = getUserSearch().searchForUser(username);
    }

    if (user == null) {
        throw new UsernameNotFoundException("User not found: " + username);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Performing LDAP compare of password attribute '" + passwordAttributeName + "' for user '"
                + user.getDn() + "'");
    }

    if (isLocalCompare()) {
        localCompareAuthenticate(user, password);
    } else {
        String encodedPassword = passwordEncoder.encodePassword(password, null);
        byte[] passwordBytes = Utf8.encode(encodedPassword);
        searchAuthenticate(user, passwordBytes, ldapTemplate);
    }

    return user;

}