Example usage for javax.naming.ldap LdapContext reconnect

List of usage examples for javax.naming.ldap LdapContext reconnect

Introduction

In this page you can find the example usage for javax.naming.ldap LdapContext reconnect.

Prototype

public void reconnect(Control[] connCtls) throws NamingException;

Source Link

Document

Reconnects to the LDAP server using the supplied controls and this context's environment.

Usage

From source file:info.jtrac.acegi.JtracLdapAuthenticationProvider.java

/**
 * displayName and mail are returned always, the map allows us to support
 * getting arbitrary properties in the future, hopefully
 *//*w  w  w  .j a  va2  s  .c  om*/
public Map<String, String> bind(String loginName, String password) throws Exception {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapUrl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    LdapContext ctx = null;
    if (activeDirectoryDomain != null) { // we are using Active Directory            
        Control[] controls = new Control[] { control };
        ctx = new InitialLdapContext(env, controls);
        logger.debug("Active Directory LDAP context initialized");
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, activeDirectoryDomain + "\\" + loginName);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
        // javax.naming.AuthenticationException
        ctx.reconnect(controls);
        logger.debug("Active Directory LDAP bind successful");
    } else { // standard LDAP            
        env.put(Context.SECURITY_PRINCIPAL, searchKey + "=" + loginName + "," + searchBase);
        env.put(Context.SECURITY_CREDENTIALS, password);
        ctx = new InitialLdapContext(env, null);
        logger.debug("Standard LDAP bind successful");
    }
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(returningAttributes);
    NamingEnumeration results = ctx.search(searchBase, searchKey + "=" + loginName, sc);
    while (results.hasMoreElements()) {
        SearchResult sr = (SearchResult) results.next();
        Attributes attrs = sr.getAttributes();
        logger.debug("attributes: " + attrs);
        Map<String, String> map = new HashMap<String, String>(returningAttributes.length);
        for (String key : returningAttributes) {
            Attribute attr = attrs.get(key);
            if (attr != null) {
                map.put(key, (String) attr.get());
            }
        }
        return map; // there should be only one anyway            
    }
    // if we reached here, there was no search result
    throw new Exception("no results returned from ldap");
}

From source file:de.sub.goobi.helper.ldap.Ldap.java

/**
 * Check if connection with login and password possible.
 *
 * @param inBenutzer//from   ww w.  j av a2  s .c o  m
 *            User object
 * @param inPasswort
 *            String
 * @return Login correct or not
 */
public boolean isUserPasswordCorrect(User inBenutzer, String inPasswort) {
    logger.debug("start login session with ldap");
    Hashtable<String, String> env = getLdapConnectionSettings();

    // Start TLS
    if (ConfigCore.getBooleanParameter("ldap_useTLS", false)) {
        logger.debug("use TLS for auth");
        env = new Hashtable<>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ConfigCore.getParameter("ldap_url"));
        env.put("java.naming.ldap.version", "3");
        LdapContext ctx = null;
        StartTlsResponse tls = null;
        try {
            ctx = new InitialLdapContext(env, null);

            // Authentication must be performed over a secure channel
            tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
            tls.negotiate();

            // Authenticate via SASL EXTERNAL mechanism using client X.509
            // certificate contained in JVM keystore
            ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, getUserDN(inBenutzer));
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, inPasswort);
            ctx.reconnect(null);
            return true;
            // Perform search for privileged attributes under authenticated
            // context

        } catch (IOException e) {
            logger.error("TLS negotiation error:", e);
            return false;
        } catch (NamingException e) {
            logger.error("JNDI error:", e);
            return false;
        } finally {
            if (tls != null) {
                try {
                    // Tear down TLS connection
                    tls.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
            if (ctx != null) {
                try {
                    // Close LDAP connection
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(e);
                }
            }
        }
    } else {
        logger.debug("don't use TLS for auth");
        if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) {
            env.put(Context.SECURITY_AUTHENTICATION, "none");
            // TODO auf passwort testen
        } else {
            env.put(Context.SECURITY_PRINCIPAL, getUserDN(inBenutzer));
            env.put(Context.SECURITY_CREDENTIALS, inPasswort);
        }
        logger.debug("ldap environment set");

        try {
            if (logger.isDebugEnabled()) {
                logger.debug("start classic ldap authentification");
                logger.debug("user DN is " + getUserDN(inBenutzer));
            }

            if (ConfigCore.getParameter("ldap_AttributeToTest") == null) {
                logger.debug("ldap attribute to test is null");
                DirContext ctx = new InitialDirContext(env);
                ctx.close();
                return true;
            } else {
                logger.debug("ldap attribute to test is not null");
                DirContext ctx = new InitialDirContext(env);

                Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer));
                Attribute la = attrs.get(ConfigCore.getParameter("ldap_AttributeToTest"));
                logger.debug("ldap attributes set");
                String test = (String) la.get(0);
                if (test.equals(ConfigCore.getParameter("ldap_ValueOfAttribute"))) {
                    logger.debug("ldap ok");
                    ctx.close();
                    return true;
                } else {
                    logger.debug("ldap not ok");
                    ctx.close();
                    return false;
                }
            }
        } catch (NamingException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("login not allowed for " + inBenutzer.getLogin(), e);
            }
            return false;
        }
    }
}

From source file:de.sub.goobi.helper.ldap.Ldap.java

/**
 * retrieve home directory of given user.
 *
 * @param inBenutzer/*w ww .  j  a va2  s .c o  m*/
 *            User object
 * @return path as string
 */
public String getUserHomeDirectory(User inBenutzer) {
    if (ConfigCore.getBooleanParameter("useLocalDirectory", false)) {
        return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin();
    }
    Hashtable<String, String> env = getLdapConnectionSettings();
    if (ConfigCore.getBooleanParameter("ldap_useTLS", false)) {

        env = new Hashtable<>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ConfigCore.getParameter("ldap_url"));
        env.put("java.naming.ldap.version", "3");
        LdapContext ctx = null;
        StartTlsResponse tls = null;
        try {
            ctx = new InitialLdapContext(env, null);

            // Authentication must be performed over a secure channel
            tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
            tls.negotiate();

            // Authenticate via SASL EXTERNAL mechanism using client X.509
            // certificate contained in JVM keystore
            ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));

            ctx.reconnect(null);

            Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer));
            Attribute la = attrs.get("homeDirectory");
            return (String) la.get(0);

            // Perform search for privileged attributes under authenticated
            // context

        } catch (IOException e) {
            logger.error("TLS negotiation error:", e);

            return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin();
        } catch (NamingException e) {

            logger.error("JNDI error:", e);

            return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin();
        } finally {
            if (tls != null) {
                try {
                    // Tear down TLS connection
                    tls.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
            if (ctx != null) {
                try {
                    // Close LDAP connection
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(e);
                }
            }
        }
    } else if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) {
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    } else {
        env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
        env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));

    }
    DirContext ctx;
    String rueckgabe = "";
    try {
        ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer));
        Attribute la = attrs.get("homeDirectory");
        rueckgabe = (String) la.get(0);
        ctx.close();
    } catch (NamingException e) {
        logger.error(e);
    }
    return rueckgabe;
}

From source file:org.fao.geonet.kernel.security.ldap.LdapUserDetailsManager.java

/**
 * 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>//from  ww w .  j  ava2s. com
 *
 * @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;
        }
    });
}

From source file:org.kitodo.production.services.data.LdapServerService.java

private URI getUserHomeDirectoryWithTLS(Hashtable<String, String> env, String userFolderBasePath, User user) {
    env.put("java.naming.ldap.version", "3");
    LdapContext ctx = null;
    StartTlsResponse tls = null;/*from ww  w .  j  av  a 2  s.  com*/
    try {
        ctx = new InitialLdapContext(env, null);

        // Authentication must be performed over a secure channel
        tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
        tls.negotiate();

        ctx.reconnect(null);

        Attributes attrs = ctx.getAttributes(buildUserDN(user));
        Attribute la = attrs.get("homeDirectory");
        return URI.create((String) la.get(0));
    } catch (IOException e) {
        logger.error("TLS negotiation error:", e);
        return Paths.get(userFolderBasePath, user.getLogin()).toUri();
    } catch (NamingException e) {
        logger.error("JNDI error:", e);
        return Paths.get(userFolderBasePath, user.getLogin()).toUri();
    } finally {
        closeConnections(ctx, tls);
    }
}

From source file:org.kitodo.production.services.data.LdapServerService.java

private boolean isPasswordCorrectForAuthWithTLS(Hashtable<String, String> env, User user, String password) {
    env.put("java.naming.ldap.version", "3");
    LdapContext ctx = null;
    StartTlsResponse tls = null;//from  w  w  w  . ja  v  a 2 s  .  co m
    try {
        ctx = new InitialLdapContext(env, null);

        // Authentication must be performed over a secure channel
        tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
        tls.negotiate();

        // Authenticate via SASL EXTERNAL mechanism using client X.509
        // certificate contained in JVM keystore
        ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, buildUserDN(user));
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
        ctx.reconnect(null);
        return true;
        // perform search for privileged attributes under authenticated context
    } catch (IOException e) {
        logger.error("TLS negotiation error:", e);
        return false;
    } catch (NamingException e) {
        logger.error("JNDI error:", e);
        return false;
    } finally {
        closeConnections(ctx, tls);
    }
}

From source file:org.kitodo.services.data.LdapServerService.java

/**
 * Check if connection with login and password possible.
 *
 * @param user/*from   w  ww . j a  v  a 2 s  .  com*/
 *            User object
 * @param password
 *            String
 * @return Login correct or not
 */
public boolean isUserPasswordCorrect(User user, String password) {
    logger.debug("start login session with ldap");
    Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer());

    // Start TLS
    if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_TLS)) {
        logger.debug("use TLS for auth");
        env.put("java.naming.ldap.version", "3");
        LdapContext ctx = null;
        StartTlsResponse tls = null;
        try {
            ctx = new InitialLdapContext(env, null);

            // Authentication must be performed over a secure channel
            tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
            tls.negotiate();

            // Authenticate via SASL EXTERNAL mechanism using client X.509
            // certificate contained in JVM keystore
            ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, buildUserDN(user));
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
            ctx.reconnect(null);
            return true;
            // Perform search for privileged attributes under authenticated
            // context

        } catch (IOException e) {
            logger.error("TLS negotiation error:", e);
            return false;
        } catch (NamingException e) {
            logger.error("JNDI error:", e);
            return false;
        } finally {
            if (tls != null) {
                try {
                    // Tear down TLS connection
                    tls.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (ctx != null) {
                try {
                    // Close LDAP connection
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    } else {
        logger.debug("don't use TLS for auth");
        if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) {
            env.put(Context.SECURITY_AUTHENTICATION, "none");
            // TODO auf passwort testen
        } else {
            env.put(Context.SECURITY_PRINCIPAL, buildUserDN(user));
            env.put(Context.SECURITY_CREDENTIALS, password);
        }
        logger.debug("ldap environment set");

        try {
            logger.debug("start classic ldap authentication");
            logger.debug("user DN is {}", buildUserDN(user));

            if (ConfigCore.getParameter(Parameters.LDAP_ATTRIBUTE_TO_TEST) == null) {
                logger.debug("ldap attribute to test is null");
                DirContext ctx = new InitialDirContext(env);
                ctx.close();
                return true;
            } else {
                logger.debug("ldap attribute to test is not null");
                DirContext ctx = new InitialDirContext(env);

                Attributes attrs = ctx.getAttributes(buildUserDN(user));
                Attribute la = attrs.get(ConfigCore.getParameter(Parameters.LDAP_ATTRIBUTE_TO_TEST));
                logger.debug("ldap attributes set");
                String test = (String) la.get(0);
                if (test.equals(ConfigCore.getParameter(Parameters.LDAP_VALUE_OF_ATTRIBUTE))) {
                    logger.debug("ldap ok");
                    ctx.close();
                    return true;
                } else {
                    logger.debug("ldap not ok");
                    ctx.close();
                    return false;
                }
            }
        } catch (NamingException e) {
            logger.debug("login not allowed for {}. Exception: {}", user.getLogin(), e);
            return false;
        }
    }
}

From source file:org.kitodo.services.data.LdapServerService.java

/**
 * Retrieve home directory of given user.
 *
 * @param user//from   w w w  .  j  a  v  a  2s .c om
 *            User object
 * @return path as URI
 */
public URI getUserHomeDirectory(User user) {

    URI userFolderBasePath = URI.create("file:///" + ConfigCore.getParameter(Parameters.DIR_USERS));

    if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_LOCAL_DIRECTORY)) {
        return userFolderBasePath.resolve(user.getLogin());
    }
    Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer());
    if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_TLS)) {

        env.put("java.naming.ldap.version", "3");
        LdapContext ctx = null;
        StartTlsResponse tls = null;
        try {
            ctx = new InitialLdapContext(env, null);

            // Authentication must be performed over a secure channel
            tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
            tls.negotiate();

            ctx.reconnect(null);

            Attributes attrs = ctx.getAttributes(buildUserDN(user));
            Attribute la = attrs.get("homeDirectory");
            return URI.create((String) la.get(0));

            // Perform search for privileged attributes under authenticated
            // context

        } catch (IOException e) {
            logger.error("TLS negotiation error:", e);

            return userFolderBasePath.resolve(user.getLogin());
        } catch (NamingException e) {

            logger.error("JNDI error:", e);

            return userFolderBasePath.resolve(user.getLogin());
        } finally {
            if (tls != null) {
                try {
                    // Tear down TLS connection
                    tls.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (ctx != null) {
                try {
                    // Close LDAP connection
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }
    if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) {
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    }
    DirContext ctx;
    URI userFolderPath = null;
    try {
        ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes(buildUserDN(user));
        Attribute ldapAttribute = attrs.get("homeDirectory");
        userFolderPath = URI.create((String) ldapAttribute.get(0));
        ctx.close();
    } catch (NamingException e) {
        logger.error(e.getMessage(), e);
    }

    if (userFolderPath != null && !userFolderPath.isAbsolute()) {
        if (userFolderPath.getPath().startsWith("/")) {
            userFolderPath = serviceManager.getFileService().deleteFirstSlashFromPath(userFolderPath);
        }
        return userFolderBasePath.resolve(userFolderPath);
    } else {
        return userFolderPath;
    }
}

From source file:org.ligoj.app.plugin.id.ldap.dao.UserLdapRepository.java

@Override
public void setPassword(final UserOrg userLdap, final String password, final String newPassword) {
    log.info("Changing password for {} ...", userLdap.getId());
    final ModificationItem[] passwordChange = { new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
            new BasicAttribute(PASSWORD_ATTRIBUTE, digest(newPassword))) };

    // Unlock account when the user is locked by ppolicy
    set(userLdap, PWD_ACCOUNT_LOCKED_ATTRIBUTE, null);

    // Authenticate the user is needed before changing the password.
    template.executeReadWrite(new ContextExecutor<>() {
        @Override//  w w  w .  j  a va  2  s  . c  o  m
        public Object executeWithContext(final DirContext dirCtx) throws NamingException {
            LdapContext ctx = (LdapContext) dirCtx;
            ctx.removeFromEnvironment(LDAP_CONNECT_POOL);
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userLdap.getDn());
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS,
                    password == null ? getTmpPassword(userLdap) : password);

            try {
                ctx.reconnect(null);
                ctx.modifyAttributes(userLdap.getDn(), passwordChange);
            } catch (final AuthenticationException e) {
                log.info("Authentication failed for {}: {}", userLdap.getId(), e.getMessage());
                throw new ValidationJsonException("password", "login");
            } catch (final InvalidAttributeValueException e) {
                log.info("Password change failed due to: {}", e.getMessage());
                throw new ValidationJsonException("password", "password-policy");
            }
            return null;
        }
    });
}

From source file:org.springframework.security.ldap.userdetails.LdapUserDetailsManager.java

private void changePasswordUsingAttributeModification(DistinguishedName userDn, String oldPassword,
        String newPassword) {/* w  w w  .j a  va 2  s .com*/

    final ModificationItem[] passwordChange = new ModificationItem[] { new ModificationItem(
            DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(passwordAttributeName, newPassword)) };

    if (oldPassword == null) {
        template.modifyAttributes(userDn, passwordChange);
        return;
    }

    template.executeReadWrite(dirCtx -> {
        LdapContext ctx = (LdapContext) dirCtx;
        ctx.removeFromEnvironment("com.sun.jndi.ldap.connect.pool");
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, LdapUtils.getFullDn(userDn, 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(userDn, passwordChange);

        return null;
    });

}