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:org.cloudifysource.rest.security.CustomLdapAuthGroupsPopulator.java

/**
 * Constructor./* ww w .j  av a2 s.  c  o  m*/
 *
 * @param contextSource supplies the contexts used to search for group membership.
 * @param groupSearchBase          if this is an empty string the search will be performed from the root DN of the
 *                                 context factory.
 */
public CustomLdapAuthGroupsPopulator(final ContextSource contextSource, final String groupSearchBase) {
    Assert.notNull(contextSource, "contextSource must not be null");
    ldapTemplate = new SpringSecurityLdapTemplate(contextSource);
    ldapTemplate.setSearchControls(searchControls);
    setGroupSearchBase(groupSearchBase);
}

From source file:org.geoserver.security.ldap.BindingLdapAuthoritiesPopulator.java

public Set<GrantedAuthority> getGroupMembershipRoles(final DirContext ctx, String userDn, String username) {
    if (getGroupSearchBase() == null) {
        return new HashSet<GrantedAuthority>();
    }/*w  w  w.  j a  v  a 2  s  .c  o  m*/

    Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();

    if (logger.isDebugEnabled()) {
        logger.debug("Searching for roles for user '" + username + "', DN = " + "'" + userDn + "', with filter "
                + groupSearchFilter + " in search base '" + getGroupSearchBase() + "'");
    }
    SpringSecurityLdapTemplate authTemplate;

    if (ctx == null) {
        authTemplate = ldapTemplate;
    } else {
        // if we have the authenticated context we build a new LdapTemplate
        // using it
        authTemplate = new SpringSecurityLdapTemplate(new ContextSource() {

            @Override
            public DirContext getReadOnlyContext() throws NamingException {
                return ctx;
            }

            @Override
            public DirContext getReadWriteContext() throws NamingException {
                return ctx;
            }

            @Override
            public DirContext getContext(String principal, String credentials) throws NamingException {
                return ctx;
            }

        });
    }
    Set<String> userRoles = authTemplate.searchForSingleAttributeValues(getGroupSearchBase(), groupSearchFilter,
            new String[] { userDn, username }, groupRoleAttribute);

    if (logger.isDebugEnabled()) {
        logger.debug("Roles from search: " + userRoles);
    }

    for (String role : userRoles) {

        if (convertToUpperCase) {
            role = role.toUpperCase();
        }

        authorities.add(new SimpleGrantedAuthority(rolePrefix + role));
    }

    return authorities;
}

From source file:org.opennms.web.springframework.security.UserGroupLdapAuthoritiesPopulator.java

public UserGroupLdapAuthoritiesPopulator(ContextSource contextSource, String groupSearchBase) {
    super(contextSource, groupSearchBase);
    this.ldapTemplate = new SpringSecurityLdapTemplate(contextSource);
    this.ldapTemplate.setSearchControls(searchControls);
}

From source file:org.springframework.security.ldap.authentication.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;//w  w w.jav a  2  s .  c  o  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 (usePasswordAttrCompare && isPasswordAttrCompare(user, password)) {
        return user;
    } else if (isLdapPasswordCompare(user, ldapTemplate, password)) {
        return user;
    }
    throw new BadCredentialsException(
            messages.getMessage("PasswordComparisonAuthenticator.badCredentials", "Bad credentials"));
}

From source file:org.springframework.security.ldap.search.FilterBasedLdapUserSearch.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//from  ww w  . j  av  a2  s. c o m
 *
 * @throws UsernameNotFoundException if no matching entry is found.
 */
@Override
public DirContextOperations searchForUser(String username) {
    if (logger.isDebugEnabled()) {
        logger.debug("Searching for user '" + username + "', with user search " + this);
    }

    SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(contextSource);

    template.setSearchControls(searchControls);

    try {

        return template.searchForSingleEntry(searchBase, searchFilter, new String[] { username });

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

From source file:org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator.java

/**
 * Constructor for group search scenarios. <tt>userRoleAttributes</tt> may still be
 * set as a property./*from   w  ww. ja  v a2  s . com*/
 *
 * @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. If null, no search will be performed.
 */
public DefaultLdapAuthoritiesPopulator(ContextSource contextSource, String groupSearchBase) {
    Assert.notNull(contextSource, "contextSource must not be null");
    this.ldapTemplate = new SpringSecurityLdapTemplate(contextSource);
    getLdapTemplate().setSearchControls(getSearchControls());
    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");
    }
}

From source file:org.unitime.timetable.spring.ldap.SpringLdapExternalUidLookup.java

@Override
public UserInfo doLookup(String uid) throws Exception {
    try {//  ww  w .  j a v  a 2 s .  c  o  m
        ContextSource source = (ContextSource) SpringApplicationContextHolder
                .getBean("unitimeLdapContextSource");

        String query = ApplicationProperty.AuthenticationLdapIdentify.value();
        String idAttributeName = ApplicationProperty.AuthenticationLdapIdAttribute.value();

        SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(source);
        DirContextOperations user = template.retrieveEntry(query.replaceAll("\\{0\\}", uid),
                new String[] { "uid", idAttributeName, "cn", "givenName", "sn", "mail" });

        if (user == null || user.getStringAttribute(idAttributeName) == null)
            return null;

        UserInfo info = new UserInfo();
        info.setExternalId(user.getStringAttribute(idAttributeName));

        info.setUserName(user.getStringAttribute("uid"));
        if (info.getUserName() == null)
            info.setUserName(uid);
        info.setName(user.getStringAttribute("cn"));
        info.setFirstName(user.getStringAttribute("givenName"));
        info.setLastName(user.getStringAttribute("sn"));
        info.setEmail(user.getStringAttribute("mail"));

        if (info.getEmail() == null) {
            String email = info.getUserName() + "@";
            for (String x : user.getNameInNamespace().split(","))
                if (x.startsWith("dc="))
                    email += (email.endsWith("@") ? "" : ".") + x.substring(3);
            if (!email.endsWith("@"))
                info.setEmail(email);
        }

        return info;
    } catch (Exception e) {
        sLog.warn("Lookup for " + uid + " failed: " + e.getMessage());
    }

    return null;
}

From source file:org.unitime.timetable.spring.ldap.SpringLdapExternalUidTranslation.java

public String uid2ext(String uid) {
    String externalIdAttribute = ApplicationProperty.AuthenticationLdapIdAttribute.value();
    if ("uid".equals(externalIdAttribute))
        return uid; // Nothing to translate
    try {//from  w  w  w . j a v  a  2  s  . c  o  m

        ContextSource source = (ContextSource) SpringApplicationContextHolder
                .getBean("unitimeLdapContextSource");

        String query = ApplicationProperty.AuthenticationLdapLogin2UserId.value();

        SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(source);
        DirContextOperations user = template.retrieveEntry(query.replaceAll("\\{0\\}", uid),
                new String[] { externalIdAttribute });

        return user == null ? null : user.getStringAttribute(externalIdAttribute);

    } catch (Exception e) {
        sLog.warn("Unable to translate uid to " + externalIdAttribute + ": " + e.getMessage());
    }

    return null;
}

From source file:org.unitime.timetable.spring.ldap.SpringLdapExternalUidTranslation.java

public String ext2uid(String externalUserId) {
    String externalIdAttribute = ApplicationProperty.AuthenticationLdapIdAttribute.value();
    if ("uid".equals(externalIdAttribute))
        return externalUserId; // Nothing to translate
    try {/*from  ww  w .  j  av a2 s  .  c  o  m*/

        ContextSource source = (ContextSource) SpringApplicationContextHolder
                .getBean("unitimeLdapContextSource");

        String query = ApplicationProperty.AuthenticationLdapUserId2Login.value().replace("%",
                externalIdAttribute);

        SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(source);
        DirContextOperations user = template.retrieveEntry(query.replaceAll("\\{0\\}", externalIdAttribute),
                new String[] { "uid" });

        return user == null ? null : user.getStringAttribute("uid");

    } catch (Exception e) {
        sLog.warn("Unable to translate " + externalIdAttribute + " to uid: " + e.getMessage());
    }
    return null;
}