Search in sources :

Example 11 with DirContextAdapter

use of org.springframework.ldap.core.DirContextAdapter in project spring-security by spring-projects.

the class SpringSecurityLdapTemplate method searchForMultipleAttributeValues.

/**
	 * Performs a search using the supplied filter and returns the values of each named
	 * attribute found in all entries matched by the search. Note that one directory entry
	 * may have several values for the attribute. Intended for role searches and similar
	 * scenarios.
	 *
	 * @param base the DN to search in
	 * @param filter search filter to use
	 * @param params the parameters to substitute in the search filter
	 * @param attributeNames the attributes' values that are to be retrieved.
	 *
	 * @return the set of String values for each attribute found in all the matching
	 * entries. The attribute name is the key for each set of values. In addition each map
	 * contains the DN as a String with the key predefined key {@link #DN_KEY}.
	 */
public Set<Map<String, List<String>>> searchForMultipleAttributeValues(final String base, final String filter, final Object[] params, final String[] attributeNames) {
    // Escape the params acording to RFC2254
    Object[] encodedParams = new String[params.length];
    for (int i = 0; i < params.length; i++) {
        encodedParams[i] = LdapEncoder.filterEncode(params[i].toString());
    }
    String formattedFilter = MessageFormat.format(filter, encodedParams);
    logger.debug("Using filter: " + formattedFilter);
    final HashSet<Map<String, List<String>>> set = new HashSet<Map<String, List<String>>>();
    ContextMapper roleMapper = new ContextMapper() {

        public Object mapFromContext(Object ctx) {
            DirContextAdapter adapter = (DirContextAdapter) ctx;
            Map<String, List<String>> record = new HashMap<String, List<String>>();
            if (attributeNames == null || attributeNames.length == 0) {
                try {
                    for (NamingEnumeration ae = adapter.getAttributes().getAll(); ae.hasMore(); ) {
                        Attribute attr = (Attribute) ae.next();
                        extractStringAttributeValues(adapter, record, attr.getID());
                    }
                } catch (NamingException x) {
                    org.springframework.ldap.support.LdapUtils.convertLdapException(x);
                }
            } else {
                for (String attributeName : attributeNames) {
                    extractStringAttributeValues(adapter, record, attributeName);
                }
            }
            record.put(DN_KEY, Arrays.asList(getAdapterDN(adapter)));
            set.add(record);
            return null;
        }
    };
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(searchControls.getSearchScope());
    ctls.setReturningAttributes(attributeNames != null && attributeNames.length > 0 ? attributeNames : null);
    search(base, formattedFilter, ctls, roleMapper);
    return set;
}
Also used : HashMap(java.util.HashMap) Attribute(javax.naming.directory.Attribute) NamingEnumeration(javax.naming.NamingEnumeration) DirContextAdapter(org.springframework.ldap.core.DirContextAdapter) ArrayList(java.util.ArrayList) List(java.util.List) NamingException(javax.naming.NamingException) SearchControls(javax.naming.directory.SearchControls) HashMap(java.util.HashMap) Map(java.util.Map) ContextMapper(org.springframework.ldap.core.ContextMapper) HashSet(java.util.HashSet)

Example 12 with DirContextAdapter

use of org.springframework.ldap.core.DirContextAdapter in project spring-security by spring-projects.

the class BindAuthenticator method bindWithDn.

private DirContextOperations bindWithDn(String userDnStr, String username, String password, Attributes attrs) {
    BaseLdapPathContextSource ctxSource = (BaseLdapPathContextSource) getContextSource();
    DistinguishedName userDn = new DistinguishedName(userDnStr);
    DistinguishedName fullDn = new DistinguishedName(userDn);
    fullDn.prepend(ctxSource.getBaseLdapPath());
    logger.debug("Attempting to bind as " + fullDn);
    DirContext ctx = null;
    try {
        ctx = getContextSource().getContext(fullDn.toString(), password);
        // Check for password policy control
        PasswordPolicyControl ppolicy = PasswordPolicyControlExtractor.extractControl(ctx);
        logger.debug("Retrieving attributes...");
        if (attrs == null || attrs.size() == 0) {
            attrs = ctx.getAttributes(userDn, getUserAttributes());
        }
        DirContextAdapter result = new DirContextAdapter(attrs, userDn, ctxSource.getBaseLdapPath());
        if (ppolicy != null) {
            result.setAttributeValue(ppolicy.getID(), ppolicy);
        }
        return result;
    } catch (NamingException e) {
        // unless a subclass wishes to implement more specialized behaviour.
        if ((e instanceof org.springframework.ldap.AuthenticationException) || (e instanceof org.springframework.ldap.OperationNotSupportedException)) {
            handleBindException(userDnStr, username, e);
        } else {
            throw e;
        }
    } catch (javax.naming.NamingException e) {
        throw LdapUtils.convertLdapException(e);
    } finally {
        LdapUtils.closeContext(ctx);
    }
    return null;
}
Also used : DistinguishedName(org.springframework.ldap.core.DistinguishedName) BaseLdapPathContextSource(org.springframework.ldap.core.support.BaseLdapPathContextSource) PasswordPolicyControl(org.springframework.security.ldap.ppolicy.PasswordPolicyControl) DirContextAdapter(org.springframework.ldap.core.DirContextAdapter) NamingException(org.springframework.ldap.NamingException) DirContext(javax.naming.directory.DirContext)

Example 13 with DirContextAdapter

use of org.springframework.ldap.core.DirContextAdapter in project spring-security by spring-projects.

the class PasswordComparisonAuthenticatorTests method testOnlySpecifiedAttributesAreRetrieved.

@Test
public void testOnlySpecifiedAttributesAreRetrieved() throws Exception {
    authenticator.setUserAttributes(new String[] { "uid", "userPassword" });
    DirContextAdapter user = (DirContextAdapter) authenticator.authenticate(bob);
    assertThat(user.getAttributes().size()).withFailMessage("Should have retrieved 2 attribute (uid)").isEqualTo(2);
}
Also used : DirContextAdapter(org.springframework.ldap.core.DirContextAdapter)

Example 14 with DirContextAdapter

use of org.springframework.ldap.core.DirContextAdapter in project spring-security by spring-projects.

the class DefaultLdapAuthoritiesPopulatorTests method subGroupRolesAreFoundWhenSubtreeSearchIsEnabled.

@Test
public void subGroupRolesAreFoundWhenSubtreeSearchIsEnabled() {
    populator.setGroupRoleAttribute("ou");
    populator.setConvertToUpperCase(true);
    populator.setSearchSubtree(true);
    DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("uid=ben,ou=people,dc=springframework,dc=org"));
    Set<String> authorities = AuthorityUtils.authorityListToSet(populator.getGrantedAuthorities(ctx, "manager"));
    assertThat(authorities).as("Should have 3 roles").hasSize(3);
    assertThat(authorities.contains("ROLE_MANAGER")).isTrue();
    assertThat(authorities.contains("ROLE_SUBMANAGER")).isTrue();
    assertThat(authorities.contains("ROLE_DEVELOPER")).isTrue();
}
Also used : DistinguishedName(org.springframework.ldap.core.DistinguishedName) DirContextAdapter(org.springframework.ldap.core.DirContextAdapter)

Example 15 with DirContextAdapter

use of org.springframework.ldap.core.DirContextAdapter in project spring-security by spring-projects.

the class DefaultLdapAuthoritiesPopulatorTests method defaultRoleIsAssignedWhenSet.

@Test
public void defaultRoleIsAssignedWhenSet() {
    populator.setDefaultRole("ROLE_USER");
    assertThat(populator.getContextSource()).isSameAs(getContextSource());
    DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName("cn=notfound"));
    Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx, "notfound");
    assertThat(authorities).hasSize(1);
    assertThat(AuthorityUtils.authorityListToSet(authorities).contains("ROLE_USER")).isTrue();
}
Also used : DistinguishedName(org.springframework.ldap.core.DistinguishedName) GrantedAuthority(org.springframework.security.core.GrantedAuthority) DirContextAdapter(org.springframework.ldap.core.DirContextAdapter)

Aggregations

DirContextAdapter (org.springframework.ldap.core.DirContextAdapter)39 DistinguishedName (org.springframework.ldap.core.DistinguishedName)28 Test (org.junit.Test)19 GrantedAuthority (org.springframework.security.core.GrantedAuthority)11 DirContext (javax.naming.directory.DirContext)7 SearchControls (javax.naming.directory.SearchControls)7 SearchResult (javax.naming.directory.SearchResult)7 Name (javax.naming.Name)4 Authentication (org.springframework.security.core.Authentication)4 HashSet (java.util.HashSet)3 BasicAttribute (javax.naming.directory.BasicAttribute)3 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)3 UserDetails (org.springframework.security.core.userdetails.UserDetails)3 List (java.util.List)2 Attribute (javax.naming.directory.Attribute)2 BasicAttributes (javax.naming.directory.BasicAttributes)2 DirContextOperations (org.springframework.ldap.core.DirContextOperations)2 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)2 MockUserSearch (org.springframework.security.ldap.authentication.MockUserSearch)2 ArrayList (java.util.ArrayList)1