Search in sources :

Example 66 with DirContextOperations

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

the class NamespaceLdapAuthenticationProviderTests method ldapAuthenticationProviderCustomLdapAuthoritiesPopulator.

// SEC-2490
@Test
public void ldapAuthenticationProviderCustomLdapAuthoritiesPopulator() throws Exception {
    LdapContextSource contextSource = new DefaultSpringSecurityContextSource("ldap://blah.example.com:789/dc=springframework,dc=org");
    CustomAuthoritiesPopulatorConfig.LAP = new DefaultLdapAuthoritiesPopulator(contextSource, null) {

        @Override
        protected Set<GrantedAuthority> getAdditionalRoles(DirContextOperations user, String username) {
            return new HashSet<>(AuthorityUtils.createAuthorityList("ROLE_EXTRA"));
        }
    };
    this.spring.register(CustomAuthoritiesPopulatorConfig.class).autowire();
    // @formatter:off
    SecurityMockMvcRequestBuilders.FormLoginRequestBuilder request = formLogin().user("bob").password("bobspassword");
    SecurityMockMvcResultMatchers.AuthenticatedMatcher user = authenticated().withAuthorities(Collections.singleton(new SimpleGrantedAuthority("ROLE_EXTRA")));
    // @formatter:on
    this.mockMvc.perform(request).andExpect(user);
}
Also used : DefaultSpringSecurityContextSource(org.springframework.security.ldap.DefaultSpringSecurityContextSource) HashSet(java.util.HashSet) Set(java.util.Set) LdapContextSource(org.springframework.ldap.core.support.LdapContextSource) DefaultLdapAuthoritiesPopulator(org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator) CustomAuthoritiesPopulatorConfig(org.springframework.security.config.annotation.authentication.ldap.NamespaceLdapAuthenticationProviderTestsConfigs.CustomAuthoritiesPopulatorConfig) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) DirContextOperations(org.springframework.ldap.core.DirContextOperations) SecurityMockMvcRequestBuilders(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders) SecurityMockMvcResultMatchers(org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers) Test(org.junit.jupiter.api.Test)

Example 67 with DirContextOperations

use of org.springframework.ldap.core.DirContextOperations 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));
    logger.trace(LogMessage.format("Searching for entry under DN '%s', base = '%s', filter = '%s'", ctxBaseDn, searchBaseDn, filter));
    Set<DirContextOperations> results = new HashSet<>();
    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");
            logger.debug(LogMessage.format("Found DN: %s", dca.getDn()));
            results.add(dca);
        }
    } catch (PartialResultException ex) {
        LdapUtils.closeEnumeration(resultsEnum);
        logger.trace("Ignoring PartialResultException");
    }
    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 68 with DirContextOperations

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

the class BindAuthenticator method authenticate.

@Override
public DirContextOperations authenticate(Authentication authentication) {
    DirContextOperations user = null;
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, "Can only process UsernamePasswordAuthenticationToken objects");
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();
    if (!StringUtils.hasLength(password)) {
        logger.debug(LogMessage.format("Failed to authenticate since no credentials provided"));
        throw new BadCredentialsException(this.messages.getMessage("BindAuthenticator.emptyPassword", "Empty Password"));
    }
    // If DN patterns are configured, try authenticating with them directly
    for (String dn : getUserDns(username)) {
        user = bindWithDn(dn, username, password);
        if (user != null) {
            break;
        }
    }
    if (user == null) {
        logger.debug(LogMessage.of(() -> "Failed to bind with any user DNs " + getUserDns(username)));
    }
    // with the returned DN.
    if (user == null && getUserSearch() != null) {
        logger.trace("Searching for user using " + getUserSearch());
        DirContextOperations userFromSearch = getUserSearch().searchForUser(username);
        user = bindWithDn(userFromSearch.getDn().toString(), username, password, userFromSearch.getAttributes());
        if (user == null) {
            logger.debug("Failed to find user using " + getUserSearch());
        }
    }
    if (user == null) {
        throw new BadCredentialsException(this.messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials"));
    }
    return user;
}
Also used : DirContextOperations(org.springframework.ldap.core.DirContextOperations) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 69 with DirContextOperations

use of org.springframework.ldap.core.DirContextOperations in project midpoint by Evolveum.

the class MidPointLdapAuthenticationProvider method createAuthenticatorProvider.

private LdapAuthenticationProvider createAuthenticatorProvider(LdapAuthenticator authenticator) {
    return new LdapAuthenticationProvider(authenticator) {

        @Override
        protected DirContextOperations doAuthentication(UsernamePasswordAuthenticationToken authentication) {
            DirContextOperations originalDirContextOperations = super.doAuthentication(authentication);
            return MidPointLdapAuthenticationProvider.this.doAuthentication(originalDirContextOperations);
        }

        @Override
        protected Authentication createSuccessfulAuthentication(UsernamePasswordAuthenticationToken authentication, UserDetails user) {
            Authentication authNCtx = super.createSuccessfulAuthentication(authentication, user);
            MidPointLdapAuthenticationProvider.this.createSuccessfulAuthentication(authentication, authNCtx);
            return authNCtx;
        }
    };
}
Also used : UserDetails(org.springframework.security.core.userdetails.UserDetails) DirContextOperations(org.springframework.ldap.core.DirContextOperations) LdapModuleAuthentication(com.evolveum.midpoint.authentication.impl.module.authentication.LdapModuleAuthentication) MidpointAuthentication(com.evolveum.midpoint.authentication.api.config.MidpointAuthentication) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) LdapAuthenticationProvider(org.springframework.security.ldap.authentication.LdapAuthenticationProvider)

Example 70 with DirContextOperations

use of org.springframework.ldap.core.DirContextOperations in project perun by CESNET.

the class PerunUserImpl method removeFromFacilityAdmins.

@Override
public void removeFromFacilityAdmins(User user, Facility facility) {
    DirContextOperations entry = findByDN(buildDN(user));
    Name facilityDN = addBaseDN(perunFacility.getEntryDN(String.valueOf(facility.getId())));
    entry.removeAttributeValue(PerunAttribute.PerunAttributeNames.ldapAttrAdminOfFacility, facilityDN.toString());
    ldapTemplate.modifyAttributes(entry);
}
Also used : DirContextOperations(org.springframework.ldap.core.DirContextOperations) Name(javax.naming.Name)

Aggregations

DirContextOperations (org.springframework.ldap.core.DirContextOperations)89 Name (javax.naming.Name)20 Test (org.junit.jupiter.api.Test)13 Test (org.junit.Test)9 UserDetails (org.springframework.security.core.userdetails.UserDetails)9 HashSet (java.util.HashSet)8 DirContextAdapter (org.springframework.ldap.core.DirContextAdapter)8 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)8 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)7 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)7 FilterBasedLdapUserSearch (org.springframework.security.ldap.search.FilterBasedLdapUserSearch)7 LdapConfig (com.thoughtworks.go.config.LdapConfig)6 BaseConfig (com.thoughtworks.go.config.server.security.ldap.BaseConfig)6 BasesConfig (com.thoughtworks.go.config.server.security.ldap.BasesConfig)6 ArrayList (java.util.ArrayList)6 Set (java.util.Set)6 NameNotFoundException (org.springframework.ldap.NameNotFoundException)6 GrantedAuthority (org.springframework.security.core.GrantedAuthority)5 PerunAttribute (cz.metacentrum.perun.ldapc.model.PerunAttribute)4 List (java.util.List)4