Search in sources :

Example 16 with DirContextOperations

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

the class DefaultLdapAuthoritiesPopulatorTests method extraRolesAreAdded.

@Test
public void extraRolesAreAdded() {
    this.populator = new DefaultLdapAuthoritiesPopulator(this.contextSource, null) {

        @Override
        protected Set<GrantedAuthority> getAdditionalRoles(DirContextOperations user, String username) {
            return new HashSet<>(AuthorityUtils.createAuthorityList("ROLE_EXTRA"));
        }
    };
    Collection<GrantedAuthority> authorities = this.populator.getGrantedAuthorities(new DirContextAdapter(new DistinguishedName("cn=notused")), "notused");
    assertThat(authorities).hasSize(1);
    assertThat(AuthorityUtils.authorityListToSet(authorities).contains("ROLE_EXTRA")).isTrue();
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) DirContextOperations(org.springframework.ldap.core.DirContextOperations) DistinguishedName(org.springframework.ldap.core.DistinguishedName) GrantedAuthority(org.springframework.security.core.GrantedAuthority) DirContextAdapter(org.springframework.ldap.core.DirContextAdapter) Test(org.junit.jupiter.api.Test)

Example 17 with DirContextOperations

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

the class AbstractLdapAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, () -> this.messages.getMessage("LdapAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported"));
    UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication;
    String username = userToken.getName();
    String password = (String) authentication.getCredentials();
    if (!StringUtils.hasLength(username)) {
        throw new BadCredentialsException(this.messages.getMessage("LdapAuthenticationProvider.emptyUsername", "Empty Username"));
    }
    if (!StringUtils.hasLength(password)) {
        throw new BadCredentialsException(this.messages.getMessage("AbstractLdapAuthenticationProvider.emptyPassword", "Empty Password"));
    }
    Assert.notNull(password, "Null password was supplied in authentication token");
    DirContextOperations userData = doAuthentication(userToken);
    UserDetails user = this.userDetailsContextMapper.mapUserFromContext(userData, authentication.getName(), loadUserAuthorities(userData, authentication.getName(), (String) authentication.getCredentials()));
    return createSuccessfulAuthentication(userToken, user);
}
Also used : UserDetails(org.springframework.security.core.userdetails.UserDetails) DirContextOperations(org.springframework.ldap.core.DirContextOperations) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 18 with DirContextOperations

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

the class FilterBasedLdapUserSearch method searchForUser.

/**
 * 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.
 */
@Override
public DirContextOperations searchForUser(String username) {
    logger.trace(LogMessage.of(() -> "Searching for user '" + username + "', with " + this));
    SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(this.contextSource);
    template.setSearchControls(this.searchControls);
    try {
        DirContextOperations operations = template.searchForSingleEntry(this.searchBase, this.searchFilter, new String[] { username });
        logger.debug(LogMessage.of(() -> "Found user '" + username + "', with " + this));
        return operations;
    } catch (IncorrectResultSizeDataAccessException ex) {
        if (ex.getActualSize() == 0) {
            throw new UsernameNotFoundException("User " + username + " not found in directory.");
        }
        // Search should never return multiple results if properly configured
        throw ex;
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) SpringSecurityLdapTemplate(org.springframework.security.ldap.SpringSecurityLdapTemplate) DirContextOperations(org.springframework.ldap.core.DirContextOperations) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException)

Example 19 with DirContextOperations

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

the class PasswordComparisonAuthenticator method authenticate.

@Override
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;
    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) {
            logger.trace(LogMessage.format("Failed to retrieve user with %s", userDn), ignore);
        }
        if (user != null) {
            break;
        }
    }
    if (user == null) {
        logger.debug(LogMessage.of(() -> "Failed to retrieve user with any user DNs " + getUserDns(username)));
    }
    if (user == null && getUserSearch() != null) {
        logger.trace("Searching for user using " + getUserSearch());
        user = getUserSearch().searchForUser(username);
        if (user == null) {
            logger.debug("Failed to find user using " + getUserSearch());
        }
    }
    if (user == null) {
        throw new UsernameNotFoundException("User not found: " + username);
    }
    if (logger.isTraceEnabled()) {
        logger.trace(LogMessage.format("Comparing password attribute '%s' for user '%s'", this.passwordAttributeName, user.getDn()));
    }
    if (this.usePasswordAttrCompare && isPasswordAttrCompare(user, password)) {
        logger.debug(LogMessage.format("Locally matched password attribute '%s' for user '%s'", this.passwordAttributeName, user.getDn()));
        return user;
    }
    if (isLdapPasswordCompare(user, ldapTemplate, password)) {
        logger.debug(LogMessage.format("LDAP-matched password attribute '%s' for user '%s'", this.passwordAttributeName, user.getDn()));
        return user;
    }
    throw new BadCredentialsException(this.messages.getMessage("PasswordComparisonAuthenticator.badCredentials", "Bad credentials"));
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) SpringSecurityLdapTemplate(org.springframework.security.ldap.SpringSecurityLdapTemplate) DirContextOperations(org.springframework.ldap.core.DirContextOperations) NameNotFoundException(org.springframework.ldap.NameNotFoundException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 20 with DirContextOperations

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

the class AbstractPerunEntry method modifyEntry.

protected void modifyEntry(T bean, Iterable<PerunAttribute<T>> attrs, List<String> attrNames) {
    DirContextOperations entry = findByDN(buildDN(bean));
    mapToContext(bean, entry, findAttributeDescriptionsByLdapName(attrs, attrNames));
    ldapTemplate.modifyAttributes(entry);
}
Also used : DirContextOperations(org.springframework.ldap.core.DirContextOperations)

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