Example usage for javax.naming.ldap LdapContext getAttributes

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

Introduction

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

Prototype

public Attributes getAttributes(Name name) throws NamingException;

Source Link

Document

Retrieves all of the attributes associated with a named object.

Usage

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

/**
 * retrieve home directory of given user.
 *
 * @param inBenutzer/*ww  w .ja  v  a 2s  .  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:de.sub.goobi.helper.ldap.Ldap.java

/**
 * Check if connection with login and password possible.
 *
 * @param inBenutzer/*from  w ww. j  a  v  a  2  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:org.apache.directory.server.core.jndi.ObjStateFactoryIT.java

@Test
public void testObjectFactory() throws Exception {
    LdifEntry akarasulu = getUserAddLdif();
    getService().getAdminSession().add(new DefaultEntry(getService().getSchemaManager(), akarasulu.getEntry()));

    LdapContext sysRoot = getSystemContext(getService());
    sysRoot.addToEnvironment(Context.OBJECT_FACTORIES, PersonObjectFactory.class.getName());
    Object obj = sysRoot.lookup("uid=akarasulu, ou=users");
    Attributes attrs = sysRoot.getAttributes("uid=akarasulu, ou=users");
    assertEquals(Person.class, obj.getClass());
    Person me = (Person) obj;/* w  w w.  j  a  v a 2s  . com*/
    assertEquals(attrs.get("sn").get(), me.getLastname());
    assertEquals(attrs.get("cn").get(), me.getCn());
    assertTrue(ArrayUtils.isEquals(attrs.get("userPassword").get(), Strings.getBytesUtf8("test")));
    assertEquals(attrs.get("telephonenumber").get(), me.getTelephoneNumber());
    assertNull(me.getSeealso());
    assertNull(me.getDescription());
}

From source file:org.apache.directory.server.core.jndi.ObjStateFactoryIT.java

@Test
public void testStateFactory() throws Exception {
    LdapContext sysRoot = getSystemContext(getService());

    sysRoot.addToEnvironment(Context.STATE_FACTORIES, PersonStateFactory.class.getName());
    Person p = new Person("Rodriguez", "Mr. Kerberos", "noices", "555-1212", "sn=erodriguez", "committer");
    sysRoot.bind("sn=Rodriguez, ou=users", p);
    Attributes attrs = sysRoot.getAttributes("sn=Rodriguez, ou=users");
    assertEquals("Rodriguez", attrs.get("sn").get());
    assertEquals("Mr. Kerberos", attrs.get("cn").get());
    assertTrue(ArrayUtils.isEquals(attrs.get("userPassword").get(), Strings.getBytesUtf8("noices")));
    assertEquals("555-1212", attrs.get("telephonenumber").get());
    assertEquals("sn=erodriguez", attrs.get("seealso").get());
    assertEquals("committer", attrs.get("description").get());
}

From source file:org.apache.james.user.ldap.ReadOnlyLDAPGroupRestriction.java

/**
 * Returns the distinguished-names (DNs) of all the members of the groups
 * specified in the restriction list. The information is organised as a list
 * of <code>&quot;&lt;groupDN&gt;=&lt;
 * [userDN1,userDN2,...,userDNn]&gt;&quot;</code>. Put differently, each
 * <code>groupDN</code> is associated to a list of <code>userDNs</code>.
 *
 * @return Returns a map of groupDNs to userDN lists.
 * @throws NamingException Propagated from underlying LDAP communication layer.
 *///from  w w  w.j  av a  2 s . co  m
protected Map<String, Collection<String>> getGroupMembershipLists(LdapContext ldapContext)
        throws NamingException {
    Map<String, Collection<String>> result = new HashMap<String, Collection<String>>();

    for (String groupDN : groupDNs) {
        result.put(groupDN, extractMembers(ldapContext.getAttributes(groupDN)));
    }

    return result;
}

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 w  w w  .  j  a v  a2  s. c o  m*/
    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.services.data.LdapServerService.java

/**
 * Check if connection with login and password possible.
 *
 * @param user//from   w  ww  . j a  v  a2 s  .co  m
 *            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/* w  w w .ja  va2s.c o m*/
 *            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;
    }
}