Search in sources :

Example 76 with SearchResult

use of javax.naming.directory.SearchResult in project spring-security by spring-projects.

the class SpringSecurityLdapTemplate method searchForSingleEntryInternal.

/**
	 * Internal method extracted to avoid code duplication in AD search.
	 */
public static DirContextOperations searchForSingleEntryInternal(DirContext ctx, SearchControls searchControls, String base, String filter, Object[] params) throws NamingException {
    final DistinguishedName ctxBaseDn = new DistinguishedName(ctx.getNameInNamespace());
    final DistinguishedName searchBaseDn = new DistinguishedName(base);
    final NamingEnumeration<SearchResult> resultsEnum = ctx.search(searchBaseDn, filter, params, buildControls(searchControls));
    if (logger.isDebugEnabled()) {
        logger.debug("Searching for entry under DN '" + ctxBaseDn + "', base = '" + searchBaseDn + "', filter = '" + filter + "'");
    }
    Set<DirContextOperations> results = new HashSet<DirContextOperations>();
    try {
        while (resultsEnum.hasMore()) {
            SearchResult searchResult = resultsEnum.next();
            DirContextAdapter dca = (DirContextAdapter) searchResult.getObject();
            Assert.notNull(dca, "No object returned by search, DirContext is not correctly configured");
            if (logger.isDebugEnabled()) {
                logger.debug("Found DN: " + dca.getDn());
            }
            results.add(dca);
        }
    } catch (PartialResultException e) {
        LdapUtils.closeEnumeration(resultsEnum);
        logger.info("Ignoring PartialResultException");
    }
    if (results.size() == 0) {
        throw new IncorrectResultSizeDataAccessException(1, 0);
    }
    if (results.size() > 1) {
        throw new IncorrectResultSizeDataAccessException(1, results.size());
    }
    return results.iterator().next();
}
Also used : DirContextOperations(org.springframework.ldap.core.DirContextOperations) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) DistinguishedName(org.springframework.ldap.core.DistinguishedName) DirContextAdapter(org.springframework.ldap.core.DirContextAdapter) SearchResult(javax.naming.directory.SearchResult) PartialResultException(javax.naming.PartialResultException) HashSet(java.util.HashSet)

Example 77 with SearchResult

use of javax.naming.directory.SearchResult in project spring-security by spring-projects.

the class LdapUserDetailsManager method getUserAuthorities.

/**
	 *
	 * @param dn the distinguished name of the entry - may be either relative to the base
	 * context or a complete DN including the name of the context (either is supported).
	 * @param username the user whose roles are required.
	 * @return the granted authorities returned by the group search
	 */
@SuppressWarnings("unchecked")
List<GrantedAuthority> getUserAuthorities(final DistinguishedName dn, final String username) {
    SearchExecutor se = new SearchExecutor() {

        public NamingEnumeration<SearchResult> executeSearch(DirContext ctx) throws NamingException {
            DistinguishedName fullDn = LdapUtils.getFullDn(dn, ctx);
            SearchControls ctrls = new SearchControls();
            ctrls.setReturningAttributes(new String[] { groupRoleAttributeName });
            return ctx.search(groupSearchBase, groupSearchFilter, new String[] { fullDn.toUrl(), username }, ctrls);
        }
    };
    AttributesMapperCallbackHandler roleCollector = new AttributesMapperCallbackHandler(roleMapper);
    template.search(se, roleCollector);
    return roleCollector.getList();
}
Also used : DistinguishedName(org.springframework.ldap.core.DistinguishedName) SearchResult(javax.naming.directory.SearchResult) SearchControls(javax.naming.directory.SearchControls) DirContext(javax.naming.directory.DirContext) SearchExecutor(org.springframework.ldap.core.SearchExecutor) AttributesMapperCallbackHandler(org.springframework.ldap.core.AttributesMapperCallbackHandler)

Example 78 with SearchResult

use of javax.naming.directory.SearchResult in project spring-security by spring-projects.

the class ActiveDirectoryLdapAuthenticationProviderTests method customSearchFilterIsUsedForSuccessfulAuthentication.

// SEC-1915
@Test
public void customSearchFilterIsUsedForSuccessfulAuthentication() throws Exception {
    // given
    String customSearchFilter = "(&(objectClass=user)(sAMAccountName={0}))";
    DirContext ctx = mock(DirContext.class);
    when(ctx.getNameInNamespace()).thenReturn("");
    DirContextAdapter dca = new DirContextAdapter();
    SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
    when(ctx.search(any(Name.class), eq(customSearchFilter), any(Object[].class), any(SearchControls.class))).thenReturn(new MockNamingEnumeration(sr));
    ActiveDirectoryLdapAuthenticationProvider customProvider = new ActiveDirectoryLdapAuthenticationProvider("mydomain.eu", "ldap://192.168.1.200/");
    customProvider.contextFactory = createContextFactoryReturning(ctx);
    // when
    customProvider.setSearchFilter(customSearchFilter);
    Authentication result = customProvider.authenticate(joe);
    // then
    assertThat(result.isAuthenticated()).isTrue();
}
Also used : Authentication(org.springframework.security.core.Authentication) DirContextAdapter(org.springframework.ldap.core.DirContextAdapter) SearchResult(javax.naming.directory.SearchResult) SearchControls(javax.naming.directory.SearchControls) DirContext(javax.naming.directory.DirContext) Name(javax.naming.Name) DistinguishedName(org.springframework.ldap.core.DistinguishedName) Test(org.junit.Test)

Example 79 with SearchResult

use of javax.naming.directory.SearchResult in project spring-security by spring-projects.

the class ActiveDirectoryLdapAuthenticationProviderTests method noUserSearchCausesUsernameNotFound.

// SEC-2017
@Test(expected = BadCredentialsException.class)
public void noUserSearchCausesUsernameNotFound() throws Exception {
    DirContext ctx = mock(DirContext.class);
    when(ctx.getNameInNamespace()).thenReturn("");
    when(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class))).thenReturn(new EmptyEnumeration<SearchResult>());
    provider.contextFactory = createContextFactoryReturning(ctx);
    provider.authenticate(joe);
}
Also used : SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) DirContext(javax.naming.directory.DirContext) Name(javax.naming.Name) DistinguishedName(org.springframework.ldap.core.DistinguishedName) Test(org.junit.Test)

Example 80 with SearchResult

use of javax.naming.directory.SearchResult in project spring-security by spring-projects.

the class ActiveDirectoryLdapAuthenticationProviderTests method nullDomainIsSupportedIfAuthenticatingWithFullUserPrincipal.

@Test
public void nullDomainIsSupportedIfAuthenticatingWithFullUserPrincipal() throws Exception {
    provider = new ActiveDirectoryLdapAuthenticationProvider(null, "ldap://192.168.1.200/");
    DirContext ctx = mock(DirContext.class);
    when(ctx.getNameInNamespace()).thenReturn("");
    DirContextAdapter dca = new DirContextAdapter();
    SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
    when(ctx.search(eq(new DistinguishedName("DC=mydomain,DC=eu")), any(String.class), any(Object[].class), any(SearchControls.class))).thenReturn(new MockNamingEnumeration(sr));
    provider.contextFactory = createContextFactoryReturning(ctx);
    try {
        provider.authenticate(joe);
        fail("Expected BadCredentialsException for user with no domain information");
    } catch (BadCredentialsException expected) {
    }
    provider.authenticate(new UsernamePasswordAuthenticationToken("joe@mydomain.eu", "password"));
}
Also used : DistinguishedName(org.springframework.ldap.core.DistinguishedName) DirContextAdapter(org.springframework.ldap.core.DirContextAdapter) SearchResult(javax.naming.directory.SearchResult) SearchControls(javax.naming.directory.SearchControls) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) DirContext(javax.naming.directory.DirContext) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Test(org.junit.Test)

Aggregations

SearchResult (javax.naming.directory.SearchResult)95 SearchControls (javax.naming.directory.SearchControls)63 NamingException (javax.naming.NamingException)43 Attributes (javax.naming.directory.Attributes)35 Attribute (javax.naming.directory.Attribute)32 ArrayList (java.util.ArrayList)29 DirContext (javax.naming.directory.DirContext)27 NamingEnumeration (javax.naming.NamingEnumeration)24 InitialDirContext (javax.naming.directory.InitialDirContext)16 Test (org.junit.Test)15 LdapContext (javax.naming.ldap.LdapContext)13 IOException (java.io.IOException)9 BasicAttributes (javax.naming.directory.BasicAttributes)9 DistinguishedName (org.springframework.ldap.core.DistinguishedName)9 DirContextAdapter (org.springframework.ldap.core.DirContextAdapter)7 HashMap (java.util.HashMap)6 HashSet (java.util.HashSet)6 Name (javax.naming.Name)6 BasicAttribute (javax.naming.directory.BasicAttribute)6 PartialResultException (javax.naming.PartialResultException)5