Search in sources :

Example 6 with DistinguishedName

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

the class LdapUserDetailsManager method buildGroupDn.

/**
	 * Creates a DN from a group name.
	 *
	 * @param group the name of the group
	 * @return the DN of the corresponding group, including the groupSearchBase
	 */
protected DistinguishedName buildGroupDn(String group) {
    DistinguishedName dn = new DistinguishedName(groupSearchBase);
    dn.add(groupRoleAttributeName, group.toLowerCase());
    return dn;
}
Also used : DistinguishedName(org.springframework.ldap.core.DistinguishedName)

Example 7 with DistinguishedName

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

the class LdapUserDetailsManager method updateUser.

public void updateUser(UserDetails user) {
    DistinguishedName dn = usernameMapper.buildDn(user.getUsername());
    logger.debug("Updating user '" + user.getUsername() + "' with DN '" + dn + "'");
    List<GrantedAuthority> authorities = getUserAuthorities(dn, user.getUsername());
    DirContextAdapter ctx = loadUserAsContext(dn, user.getUsername());
    ctx.setUpdateMode(true);
    copyToContext(user, ctx);
    // Remove the objectclass attribute from the list of mods (if present).
    List<ModificationItem> mods = new LinkedList<ModificationItem>(Arrays.asList(ctx.getModificationItems()));
    ListIterator<ModificationItem> modIt = mods.listIterator();
    while (modIt.hasNext()) {
        ModificationItem mod = (ModificationItem) modIt.next();
        Attribute a = mod.getAttribute();
        if ("objectclass".equalsIgnoreCase(a.getID())) {
            modIt.remove();
        }
    }
    template.modifyAttributes(dn, mods.toArray(new ModificationItem[mods.size()]));
    // template.rebind(dn, ctx, null);
    // Remove the old authorities and replace them with the new one
    removeAuthorities(dn, authorities);
    addAuthorities(dn, user.getAuthorities());
}
Also used : ModificationItem(javax.naming.directory.ModificationItem) DistinguishedName(org.springframework.ldap.core.DistinguishedName) BasicAttribute(javax.naming.directory.BasicAttribute) Attribute(javax.naming.directory.Attribute) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) DirContextAdapter(org.springframework.ldap.core.DirContextAdapter) LinkedList(java.util.LinkedList)

Example 8 with DistinguishedName

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

the class LdapUserDetailsManager method changePassword.

/**
	 * Changes the password for the current user. The username is obtained from the
	 * security context.
	 * <p>
	 * If the old password is supplied, the update will be made by rebinding as the user,
	 * thus modifying the password using the user's permissions. If
	 * <code>oldPassword</code> is null, the update will be attempted using a standard
	 * read/write context supplied by the context source.
	 * </p>
	 *
	 * @param oldPassword the old password
	 * @param newPassword the new value of the password.
	 */
public void changePassword(final String oldPassword, final String newPassword) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Assert.notNull(authentication, "No authentication object found in security context. Can't change current user's password!");
    String username = authentication.getName();
    logger.debug("Changing password for user '" + username);
    final DistinguishedName dn = usernameMapper.buildDn(username);
    final ModificationItem[] passwordChange = new ModificationItem[] { new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(passwordAttributeName, newPassword)) };
    if (oldPassword == null) {
        template.modifyAttributes(dn, passwordChange);
        return;
    }
    template.executeReadWrite(new ContextExecutor() {

        public Object executeWithContext(DirContext dirCtx) throws NamingException {
            LdapContext ctx = (LdapContext) dirCtx;
            ctx.removeFromEnvironment("com.sun.jndi.ldap.connect.pool");
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, LdapUtils.getFullDn(dn, ctx).toString());
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, oldPassword);
            // TODO: reconnect doesn't appear to actually change the credentials
            try {
                ctx.reconnect(null);
            } catch (javax.naming.AuthenticationException e) {
                throw new BadCredentialsException("Authentication for password change failed.");
            }
            ctx.modifyAttributes(dn, passwordChange);
            return null;
        }
    });
}
Also used : BasicAttribute(javax.naming.directory.BasicAttribute) DistinguishedName(org.springframework.ldap.core.DistinguishedName) DirContext(javax.naming.directory.DirContext) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) ContextExecutor(org.springframework.ldap.core.ContextExecutor) ModificationItem(javax.naming.directory.ModificationItem) Authentication(org.springframework.security.core.Authentication) NamingException(javax.naming.NamingException) LdapContext(javax.naming.ldap.LdapContext)

Example 9 with DistinguishedName

use of org.springframework.ldap.core.DistinguishedName 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 10 with DistinguishedName

use of org.springframework.ldap.core.DistinguishedName 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)

Aggregations

DistinguishedName (org.springframework.ldap.core.DistinguishedName)32 DirContextAdapter (org.springframework.ldap.core.DirContextAdapter)23 Test (org.junit.Test)8 GrantedAuthority (org.springframework.security.core.GrantedAuthority)7 DirContext (javax.naming.directory.DirContext)5 BasicAttribute (javax.naming.directory.BasicAttribute)4 SearchResult (javax.naming.directory.SearchResult)4 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)4 BasicAttributes (javax.naming.directory.BasicAttributes)2 ModificationItem (javax.naming.directory.ModificationItem)2 SearchControls (javax.naming.directory.SearchControls)2 DirContextOperations (org.springframework.ldap.core.DirContextOperations)2 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)2 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)2 Authentication (org.springframework.security.core.Authentication)2 UserDetails (org.springframework.security.core.userdetails.UserDetails)2 MockUserSearch (org.springframework.security.ldap.authentication.MockUserSearch)2 HashSet (java.util.HashSet)1 LinkedList (java.util.LinkedList)1 NamingException (javax.naming.NamingException)1