Search in sources :

Example 16 with LdapContext

use of javax.naming.ldap.LdapContext in project killbill by killbill.

the class KillBillJndiLdapRealm method findLDAPGroupsForUser.

private Set<String> findLDAPGroupsForUser(final PrincipalCollection principals, final LdapContextFactory ldapContextFactory) throws NamingException {
    final String username = (String) getAvailablePrincipal(principals);
    LdapContext systemLdapCtx = null;
    try {
        systemLdapCtx = ldapContextFactory.getSystemLdapContext();
        return findLDAPGroupsForUser(username, systemLdapCtx);
    } catch (AuthenticationException ex) {
        log.info("LDAP authentication exception='{}'", ex.getLocalizedMessage());
        return ImmutableSet.<String>of();
    } finally {
        LdapUtils.closeContext(systemLdapCtx);
    }
}
Also used : AuthenticationException(org.apache.shiro.authc.AuthenticationException) LdapContext(javax.naming.ldap.LdapContext)

Example 17 with LdapContext

use of javax.naming.ldap.LdapContext in project spring-security by spring-projects.

the class PasswordPolicyAwareContextSource method getContext.

@Override
public DirContext getContext(String principal, String credentials) throws PasswordPolicyException {
    if (principal.equals(userDn)) {
        return super.getContext(principal, credentials);
    }
    final boolean debug = logger.isDebugEnabled();
    if (debug) {
        logger.debug("Binding as '" + userDn + "', prior to reconnect as user '" + principal + "'");
    }
    // First bind as manager user before rebinding as the specific principal.
    LdapContext ctx = (LdapContext) super.getContext(userDn, password);
    Control[] rctls = { new PasswordPolicyControl(false) };
    try {
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, principal);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials);
        ctx.reconnect(rctls);
    } catch (javax.naming.NamingException ne) {
        PasswordPolicyResponseControl ctrl = PasswordPolicyControlExtractor.extractControl(ctx);
        if (debug) {
            logger.debug("Failed to obtain context", ne);
            logger.debug("Password policy response: " + ctrl);
        }
        LdapUtils.closeContext(ctx);
        if (ctrl != null) {
            if (ctrl.isLocked()) {
                throw new PasswordPolicyException(ctrl.getErrorStatus());
            }
        }
        throw LdapUtils.convertLdapException(ne);
    }
    if (debug) {
        logger.debug("PPolicy control returned: " + PasswordPolicyControlExtractor.extractControl(ctx));
    }
    return ctx;
}
Also used : Control(javax.naming.ldap.Control) LdapContext(javax.naming.ldap.LdapContext)

Example 18 with LdapContext

use of javax.naming.ldap.LdapContext in project spring-security by spring-projects.

the class PasswordPolicyControlExtractor method extractControl.

public static PasswordPolicyResponseControl extractControl(DirContext dirCtx) {
    LdapContext ctx = (LdapContext) dirCtx;
    Control[] ctrls = null;
    try {
        ctrls = ctx.getResponseControls();
    } catch (javax.naming.NamingException e) {
        logger.error("Failed to obtain response controls", e);
    }
    for (int i = 0; ctrls != null && i < ctrls.length; i++) {
        if (ctrls[i] instanceof PasswordPolicyResponseControl) {
            return (PasswordPolicyResponseControl) ctrls[i];
        }
    }
    return null;
}
Also used : Control(javax.naming.ldap.Control) LdapContext(javax.naming.ldap.LdapContext)

Example 19 with LdapContext

use of javax.naming.ldap.LdapContext 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 20 with LdapContext

use of javax.naming.ldap.LdapContext in project aries by apache.

the class InitialContextTest method testLookFromLdapICF.

@Test
public void testLookFromLdapICF() throws Exception {
    InitialContextFactoryBuilder icf = Skeleton.newMock(InitialContextFactoryBuilder.class);
    bc.registerService(new String[] { InitialContextFactoryBuilder.class.getName(), icf.getClass().getName() }, icf, (Dictionary) new Properties());
    LdapContext backCtx = Skeleton.newMock(LdapContext.class);
    InitialContextFactory fac = Skeleton.newMock(InitialContextFactory.class);
    Skeleton.getSkeleton(fac).setReturnValue(new MethodCall(InitialContextFactory.class, "getInitialContext", Hashtable.class), backCtx);
    Skeleton.getSkeleton(icf).setReturnValue(new MethodCall(InitialContextFactoryBuilder.class, "createInitialContextFactory", Hashtable.class), fac);
    Properties props = new Properties();
    props.put(JNDIConstants.BUNDLE_CONTEXT, bc);
    props.put(Context.INITIAL_CONTEXT_FACTORY, "dummy.factory");
    InitialLdapContext ilc = new InitialLdapContext(props, new Control[0]);
    ExtendedRequest req = Skeleton.newMock(ExtendedRequest.class);
    ilc.extendedOperation(req);
    Skeleton.getSkeleton(backCtx).assertCalled(new MethodCall(LdapContext.class, "extendedOperation", req));
}
Also used : InitialContextFactoryBuilder(javax.naming.spi.InitialContextFactoryBuilder) Hashtable(java.util.Hashtable) ExtendedRequest(javax.naming.ldap.ExtendedRequest) InitialLdapContext(javax.naming.ldap.InitialLdapContext) Properties(java.util.Properties) InitialContextFactory(javax.naming.spi.InitialContextFactory) MethodCall(org.apache.aries.unittest.mocks.MethodCall) InitialLdapContext(javax.naming.ldap.InitialLdapContext) LdapContext(javax.naming.ldap.LdapContext) Test(org.junit.Test)

Aggregations

LdapContext (javax.naming.ldap.LdapContext)43 NamingException (javax.naming.NamingException)14 SearchResult (javax.naming.directory.SearchResult)13 NamingEnumeration (javax.naming.NamingEnumeration)10 SearchControls (javax.naming.directory.SearchControls)9 InitialLdapContext (javax.naming.ldap.InitialLdapContext)9 IOException (java.io.IOException)8 Attributes (javax.naming.directory.Attributes)8 Test (org.junit.Test)7 ArrayList (java.util.ArrayList)6 Control (javax.naming.ldap.Control)6 Hashtable (java.util.Hashtable)5 SortControl (javax.naming.ldap.SortControl)4 JndiLdapContextFactory (org.apache.shiro.realm.ldap.JndiLdapContextFactory)4 Attribute (javax.naming.directory.Attribute)3 BasicAttribute (javax.naming.directory.BasicAttribute)3 BasicAttributes (javax.naming.directory.BasicAttributes)3 DirContext (javax.naming.directory.DirContext)3 StartTlsRequest (javax.naming.ldap.StartTlsRequest)3 GroupNotFoundException (org.jivesoftware.openfire.group.GroupNotFoundException)3