Search in sources :

Example 16 with DirContext

use of javax.naming.directory.DirContext 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 17 with DirContext

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

the class LdapUtilsTests method testGetRelativeNameReturnsEmptyStringForDnEqualToBaseName.

@Test
public void testGetRelativeNameReturnsEmptyStringForDnEqualToBaseName() throws Exception {
    final DirContext mockCtx = mock(DirContext.class);
    when(mockCtx.getNameInNamespace()).thenReturn("dc=springframework,dc=org");
    assertThat(LdapUtils.getRelativeName("dc=springframework,dc=org", mockCtx)).isEqualTo("");
}
Also used : DirContext(javax.naming.directory.DirContext) Test(org.junit.Test)

Example 18 with DirContext

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

the class LdapUtilsTests method testGetRelativeNameReturnsFullDnWithEmptyBaseName.

@Test
public void testGetRelativeNameReturnsFullDnWithEmptyBaseName() throws Exception {
    final DirContext mockCtx = mock(DirContext.class);
    when(mockCtx.getNameInNamespace()).thenReturn("");
    assertThat(LdapUtils.getRelativeName("cn=jane,dc=springframework,dc=org", mockCtx)).isEqualTo("cn=jane,dc=springframework,dc=org");
}
Also used : DirContext(javax.naming.directory.DirContext) Test(org.junit.Test)

Example 19 with DirContext

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

the class LdapUtilsTests method testCloseContextSwallowsNamingException.

// ~ Methods
// ========================================================================================================
@Test
public void testCloseContextSwallowsNamingException() throws Exception {
    final DirContext dirCtx = mock(DirContext.class);
    doThrow(new NamingException()).when(dirCtx).close();
    LdapUtils.closeContext(dirCtx);
}
Also used : NamingException(javax.naming.NamingException) DirContext(javax.naming.directory.DirContext) Test(org.junit.Test)

Example 20 with DirContext

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

the class SpringSecurityLdapTemplate method compare.

// ~ Methods
// ========================================================================================================
/**
	 * Performs an LDAP compare operation of the value of an attribute for a particular
	 * directory entry.
	 *
	 * @param dn the entry who's attribute is to be used
	 * @param attributeName the attribute who's value we want to compare
	 * @param value the value to be checked against the directory value
	 *
	 * @return true if the supplied value matches that in the directory
	 */
public boolean compare(final String dn, final String attributeName, final Object value) {
    final String comparisonFilter = "(" + attributeName + "={0})";
    class LdapCompareCallback implements ContextExecutor {

        public Object executeWithContext(DirContext ctx) throws NamingException {
            SearchControls ctls = new SearchControls();
            ctls.setReturningAttributes(NO_ATTRS);
            ctls.setSearchScope(SearchControls.OBJECT_SCOPE);
            NamingEnumeration<SearchResult> results = ctx.search(dn, comparisonFilter, new Object[] { value }, ctls);
            Boolean match = Boolean.valueOf(results.hasMore());
            LdapUtils.closeEnumeration(results);
            return match;
        }
    }
    Boolean matches = (Boolean) executeReadOnly(new LdapCompareCallback());
    return matches.booleanValue();
}
Also used : SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) DirContext(javax.naming.directory.DirContext) ContextExecutor(org.springframework.ldap.core.ContextExecutor)

Aggregations

DirContext (javax.naming.directory.DirContext)76 NamingException (javax.naming.NamingException)32 InitialDirContext (javax.naming.directory.InitialDirContext)32 SearchResult (javax.naming.directory.SearchResult)26 SearchControls (javax.naming.directory.SearchControls)22 Attributes (javax.naming.directory.Attributes)18 Attribute (javax.naming.directory.Attribute)16 NamingEnumeration (javax.naming.NamingEnumeration)14 Test (org.junit.Test)14 Hashtable (java.util.Hashtable)12 DistinguishedName (org.springframework.ldap.core.DistinguishedName)11 Name (javax.naming.Name)7 DirContextAdapter (org.springframework.ldap.core.DirContextAdapter)7 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 BasicAttribute (javax.naming.directory.BasicAttribute)6 BasicAttributes (javax.naming.directory.BasicAttributes)6 Authentication (org.springframework.security.core.Authentication)5 Principal (java.security.Principal)3 LdapContext (javax.naming.ldap.LdapContext)3