Example usage for javax.naming.directory InitialDirContext InitialDirContext

List of usage examples for javax.naming.directory InitialDirContext InitialDirContext

Introduction

In this page you can find the example usage for javax.naming.directory InitialDirContext InitialDirContext.

Prototype

public InitialDirContext(Hashtable<?, ?> environment) throws NamingException 

Source Link

Document

Constructs an initial DirContext using the supplied environment.

Usage

From source file:org.springframework.ldap.odm.tools.SchemaToJava.java

private static ObjectSchema readSchema(String url, String user, String pass,
        SyntaxToJavaClass syntaxToJavaClass, Set<String> binarySet, Set<String> objectClasses)
        throws NamingException, ClassNotFoundException {

    // Set up environment 
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    if (user != null) {
        env.put(Context.SECURITY_PRINCIPAL, user);
    }/*  w w  w .jav a 2s.c  o m*/
    if (pass != null) {
        env.put(Context.SECURITY_CREDENTIALS, pass);
    }

    DirContext context = new InitialDirContext(env);
    DirContext schemaContext = context.getSchema("");
    SchemaReader reader = new SchemaReader(schemaContext, syntaxToJavaClass, binarySet);
    ObjectSchema schema = reader.getObjectSchema(objectClasses);

    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("Schema - %1$s", schema.toString()));
    }

    return schema;
}

From source file:com.alfaariss.oa.authentication.password.jndi.JNDIProtocolResource.java

private boolean doBind(String sUserID, String sPassword) throws OAException, UserException {
    StringBuffer sbTemp = null;/*from   ww  w . java 2 s.  co m*/
    DirContext oDirContext = null;
    String sQuery = null;
    String sRelUserDn = null;
    boolean bResult = false;
    NamingEnumeration enumSearchResults = null;

    Hashtable<String, String> htEnvironment = new Hashtable<String, String>();

    htEnvironment.put(Context.PROVIDER_URL, _sJNDIUrl);
    htEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, _sDriver);
    htEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple");

    if (_bSSL) {
        htEnvironment.put(Context.SECURITY_PROTOCOL, "ssl");
    }

    if (_sPrincipalDn.length() <= 0)
    // If no principal dn is known, we do a simple binding
    {
        String sEscUserID = JNDIUtil.escapeDN(sUserID);
        _logger.debug("Escaped user: " + sEscUserID);
        sbTemp = new StringBuffer(_sUserDn);
        sbTemp.append('=');
        sbTemp.append(sEscUserID);
        sbTemp.append(", ");
        sbTemp.append(_sBaseDn);
        htEnvironment.put(Context.SECURITY_PRINCIPAL, sbTemp.toString());

        htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
            bResult = true;
        } catch (AuthenticationException e) {
            // If supplied credentials are invalid or when authentication fails
            // while accessing the directory or naming service.
            _logger.debug("Could not authenticate user (invalid password): " + sUserID, e);
        } catch (CommunicationException eC) {
            // If communication with the directory or naming service fails.
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            // The initial dir context could not be created.
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } finally {

            try {
                if (oDirContext != null) {
                    oDirContext.close();
                }
            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + '\'', e);
            }
        }
    } else //search through the subtree
    {
        // 1 - Try to bind to LDAP using the security principal's DN and its password
        htEnvironment.put(Context.SECURITY_PRINCIPAL, _sPrincipalDn);
        htEnvironment.put(Context.SECURITY_CREDENTIALS, _sPrincipalPwd);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
        } catch (AuthenticationException eA) {
            _logger.warn("Could not bind to LDAP server", eA);
            throw new OAException(SystemErrors.ERROR_RESOURCE_CONNECT);
        } catch (CommunicationException eC) {
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        // 2 - Search through the context for user's DN relative to the base DN
        sQuery = resolveSearchQuery(sUserID);

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);

        try {
            enumSearchResults = oDirContext.search(_sBaseDn, sQuery, oScope);
        } catch (NamingException eN) {
            _logger.warn("User id not found in password backend for user: " + sUserID, eN);
            throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED);
        } finally {
            try {

                oDirContext.close();
                oDirContext = null;

            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + "'", e);
            }
        }

        try {
            if (!enumSearchResults.hasMoreElements()) {
                StringBuffer sb = new StringBuffer("User '");
                sb.append(sUserID);
                sb.append("' not found during LDAP search. The filter was: '");
                sb.append(sQuery);
                sb.append("'");
                _logger.warn(sb.toString());
                throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED);
            }

            SearchResult searchResult = (SearchResult) enumSearchResults.next();
            sRelUserDn = searchResult.getName();
            if (sRelUserDn == null) {
                _logger.warn("no user dn was returned for '" + sUserID + "'.");
                throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
            }
        } catch (NamingException eN) {

            _logger.warn("failed to fetch profile of user '" + sUserID + "'.", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        // 3 - Bind user using supplied credentials
        sbTemp = new StringBuffer(sRelUserDn);
        sbTemp.append(",");
        sbTemp.append(_sBaseDn);

        htEnvironment.put(Context.SECURITY_PRINCIPAL, sbTemp.toString());
        htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword);

        try {
            oDirContext = new InitialDirContext(htEnvironment);
            bResult = true;
        } catch (AuthenticationException e) {
            _logger.debug("Could not authenticate user (invalid password): " + sUserID, e);
        } catch (CommunicationException eC) {
            _logger.warn("A communication error has occured", eC);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } catch (NamingException eN) {
            _logger.warn("A naming error has occured", eN);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        } finally {
            try {
                if (oDirContext != null) {
                    oDirContext.close();
                }
            } catch (Exception e) {
                _logger.warn("Could not close connection with '" + _sJNDIUrl + "'.", e);
            }
        }
    }
    return bResult;
}

From source file:org.wso2.carbon.user.core.ldap.LDAPConnectionContext.java

private void populateDCMap() throws UserStoreException {
    try {//from  ww  w.j  a  v  a  2s. c om
        //get the directory context for DNS
        DirContext dnsContext = new InitialDirContext(environmentForDNS);
        //compose the DNS service to be queried
        String DNSServiceName = LDAPConstants.ACTIVE_DIRECTORY_DOMAIN_CONTROLLER_SERVICE + DNSDomainName;
        //query the DNS
        Attributes attributes = dnsContext.getAttributes(DNSServiceName,
                new String[] { LDAPConstants.SRV_ATTRIBUTE_NAME });
        Attribute srvRecords = attributes.get(LDAPConstants.SRV_ATTRIBUTE_NAME);
        //there can be multiple records with same domain name - get them all
        NamingEnumeration srvValues = srvRecords.getAll();
        dcMap = new TreeMap<Integer, SRVRecord>();
        //extract all SRV Records for _ldap._tcp service under the specified domain and populate dcMap
        //int forcedPriority = 0;
        while (srvValues.hasMore()) {
            String value = srvValues.next().toString();
            SRVRecord srvRecord = new SRVRecord();
            String valueItems[] = value.split(" ");
            String priority = valueItems[0];
            if (priority != null) {
                int priorityInt = Integer.parseInt(priority);

                /*if ((priorityInt == forcedPriority) || (priorityInt < forcedPriority)) {
                forcedPriority++;
                priorityInt = forcedPriority;
                }*/
                srvRecord.setPriority(priorityInt);
            } /* else {
              forcedPriority++;
              srvRecord.setPriority(forcedPriority);
              }*/
            String weight = valueItems[1];
            if (weight != null) {
                srvRecord.setWeight(Integer.parseInt(weight));
            }
            String port = valueItems[2];
            if (port != null) {
                srvRecord.setPort(Integer.parseInt(port));
            }
            String host = valueItems[3];
            if (host != null) {
                srvRecord.setHostName(host);
            }
            //we index dcMap on priority basis, therefore, priorities must be different
            dcMap.put(srvRecord.getPriority(), srvRecord);
        }
        //iterate over the SRVRecords for Active Directory Domain Controllers and figure out the
        //host records for that
        for (SRVRecord srvRecord : dcMap.values()) {
            Attributes hostAttributes = dnsContext.getAttributes(srvRecord.getHostName(),
                    new String[] { LDAPConstants.A_RECORD_ATTRIBUTE_NAME });
            Attribute hostRecord = hostAttributes.get(LDAPConstants.A_RECORD_ATTRIBUTE_NAME);
            //we know there is only one IP value for a given host. So we do just get, not getAll
            srvRecord.setHostIP((String) hostRecord.get());
        }
    } catch (NamingException e) {
        log.error("Error obtaining information from DNS Server" + e.getMessage(), e);
        throw new UserStoreException("Error obtaining information from DNS Server " + e.getMessage(), e);
    }
}

From source file:org.sonar.plugins.activedirectory.server.ApacheDS.java

/**
 * This seems to be required for objectClass posixGroup.
 *//*from   w w w  .  ja  va 2s .  co m*/
private ApacheDS activateNis() throws Exception {
    Preconditions.checkState(ldapServer.isStarted());

    Attribute disabled = new BasicAttribute("m-disabled", "TRUE");
    Attribute disabled2 = new BasicAttribute("m-disabled", "FALSE");
    ModificationItem[] mods = new ModificationItem[] {
            new ModificationItem(DirContext.REMOVE_ATTRIBUTE, disabled),
            new ModificationItem(DirContext.ADD_ATTRIBUTE, disabled2) };

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, getUrl());

    DirContext ctx = new InitialDirContext(env);
    ctx.modifyAttributes("cn=nis,ou=schema", mods);

    return this;
}

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

/**
 * Retrieve home directory of given user.
 *
 * @param user//w  ww .ja v a 2 s  . co  m
 *            User object
 * @return path as URI
 */
public URI getUserHomeDirectory(User user) {
    String userFolderBasePath = ConfigCore.getParameter(ParameterCore.DIR_USERS);

    if (ConfigCore.getBooleanParameterOrDefaultValue(ParameterCore.LDAP_USE_LOCAL_DIRECTORY)) {
        return Paths.get(userFolderBasePath, user.getLogin()).toUri();
    }
    Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer());
    if (ConfigCore.getBooleanParameterOrDefaultValue(ParameterCore.LDAP_USE_TLS)) {
        return getUserHomeDirectoryWithTLS(env, userFolderBasePath, user);
    }

    if (ConfigCore.getBooleanParameter(ParameterCore.LDAP_USE_SIMPLE_AUTH, 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 (Objects.nonNull(userFolderPath) && !userFolderPath.isAbsolute()) {
        if (userFolderPath.getPath().startsWith("/")) {
            userFolderPath = ServiceManager.getFileService().deleteFirstSlashFromPath(userFolderPath);
        }
        return Paths.get(userFolderBasePath, userFolderPath.getRawPath()).toUri();
    } else {
        return userFolderPath;
    }
}

From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java

/**
 * Setup environment./*from   www  .j  av  a  2  s  . c  om*/
 * @param props 
 * @throws SourceUnavailableException
 */
protected void setupEnvironment(Properties props) throws SourceUnavailableException {
    this.environment.put("com.sun.jndi.ldap.connect.pool", "true");

    this.environment.put(Context.INITIAL_CONTEXT_FACTORY, props.getProperty("INITIAL_CONTEXT_FACTORY"));
    this.environment.put(Context.PROVIDER_URL, props.getProperty("PROVIDER_URL"));
    this.environment.put(Context.SECURITY_AUTHENTICATION, props.getProperty("SECURITY_AUTHENTICATION"));
    this.environment.put(Context.SECURITY_PRINCIPAL, props.getProperty("SECURITY_PRINCIPAL"));

    String password = props.getProperty("SECURITY_CREDENTIALS");
    password = Morph.decryptIfFile(password);

    this.environment.put(Context.SECURITY_CREDENTIALS, password);
    if (props.getProperty("SECURITY_PROTOCOL") != null) {
        this.environment.put(Context.SECURITY_PROTOCOL, "ssl");
    }
    Context context = null;
    try {
        log.debug("Creating Directory Context");
        context = new InitialDirContext(this.environment);
    } catch (AuthenticationException ex) {
        log.error("Error with Authentication " + ex.getMessage(), ex);
        throw new SourceUnavailableException("Error with Authentication ", ex);
    } catch (NamingException ex) {
        log.error("Naming Error " + ex.getMessage(), ex);
        throw new SourceUnavailableException("Naming Error", ex);
    } finally {
        if (context != null) {
            try {
                context.close();
            } catch (NamingException ne) {
                // squelch, since it is already closed
            }
        }
    }
    log.info("Success in connecting to LDAP");

    this.nameAttributeName = props.getProperty("Name_AttributeType");
    if (this.nameAttributeName == null) {
        log.error("Name_AttributeType not defined");
    }
    this.subjectIDAttributeName = props.getProperty("SubjectID_AttributeType");
    if (this.subjectIDAttributeName == null) {
        log.error("SubjectID_AttributeType not defined");
    }
    this.descriptionAttributeName = props.getProperty("Description_AttributeType");
    if (this.descriptionAttributeName == null) {
        log.error("Description_AttributeType not defined");
    }

}

From source file:edu.umich.ctools.sectionsUtilityTool.SectionUtilityToolFilter.java

private boolean ldapAuthorizationVerification(String user) {
    M_log.debug("ldapAuthorizationVerification(): called");
    boolean isAuthorized = false;
    DirContext dirContext = null;
    NamingEnumeration listOfPeopleInAuthGroup = null;
    NamingEnumeration allSearchResultAttributes = null;
    NamingEnumeration simpleListOfPeople = null;
    Hashtable<String, String> env = new Hashtable<String, String>();
    if (!isEmpty(providerURL) && !isEmpty(mcommunityGroup)) {
        env.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_CTX_FACTORY);
        env.put(Context.PROVIDER_URL, providerURL);
    } else {/*from   w w w .j av  a  2 s.  c  o m*/
        M_log.error(
                " [ldap.server.url] or [mcomm.group] properties are not set, review the sectionsToolPropsLessSecure.properties file");
        return isAuthorized;
    }
    try {
        dirContext = new InitialDirContext(env);
        String[] attrIDs = { "member" };
        SearchControls searchControls = new SearchControls();
        searchControls.setReturningAttributes(attrIDs);
        searchControls.setReturningObjFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String searchBase = OU_GROUPS;
        String filter = "(&(cn=" + mcommunityGroup + ") (objectclass=rfc822MailGroup))";
        listOfPeopleInAuthGroup = dirContext.search(searchBase, filter, searchControls);
        String positiveMatch = "uid=" + user + ",";
        outerloop: while (listOfPeopleInAuthGroup.hasMore()) {
            SearchResult searchResults = (SearchResult) listOfPeopleInAuthGroup.next();
            allSearchResultAttributes = (searchResults.getAttributes()).getAll();
            while (allSearchResultAttributes.hasMoreElements()) {
                Attribute attr = (Attribute) allSearchResultAttributes.nextElement();
                simpleListOfPeople = attr.getAll();
                while (simpleListOfPeople.hasMoreElements()) {
                    String val = (String) simpleListOfPeople.nextElement();
                    if (val.indexOf(positiveMatch) != -1) {
                        isAuthorized = true;
                        break outerloop;
                    }
                }
            }
        }
        return isAuthorized;
    } catch (NamingException e) {
        M_log.error("Problem getting attribute:" + e);
        return isAuthorized;
    } finally {
        try {
            if (simpleListOfPeople != null) {
                simpleListOfPeople.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration list \"simpleListOfPeople\" list ",
                    e);
        }
        try {
            if (allSearchResultAttributes != null) {
                allSearchResultAttributes.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration \"allSearchResultAttributes\" list ",
                    e);
        }
        try {
            if (listOfPeopleInAuthGroup != null) {
                listOfPeopleInAuthGroup.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration \"listOfPeopleInAuthGroup\" list ",
                    e);
        }
        try {
            if (dirContext != null) {
                dirContext.close();
            }
        } catch (NamingException e) {
            M_log.error("Problem occurred while closing the  \"dirContext\"  object", e);
        }
    }

}

From source file:no.smint.anthropos.ldap.LDAP.java

public static String getDn(String uid) throws NamingException {
    Hashtable<String, Object> env = config();
    DirContext ctx = new InitialDirContext(env);
    SearchControls ctls = new SearchControls();
    String filter = ("uid=" + uid);
    NamingEnumeration answer = ctx.search(name, filter, ctls);

    SearchResult searchResult;//from w w w .  jav  a2 s .  c  om

    if (answer.hasMoreElements()) {
        searchResult = (SearchResult) answer.next();
    } else {
        System.out.println("Found no user by that name");
        return null;
    }
    if (answer.hasMoreElements()) {
        System.err.println("Matched mutliple users for the uid" + uid);
        return null;
    }
    ctx.close();
    return searchResult.getNameInNamespace();
}

From source file:com.alfaariss.oa.engine.attribute.gather.processor.jndi.JNDIGatherer.java

/**
 * Gathers attributes from JNDI storage to the supplied attributes object.
 * @see com.alfaariss.oa.engine.core.attribute.gather.processor.IProcessor#process(java.lang.String, com.alfaariss.oa.api.attribute.IAttributes)
 *//*from w  ww.  jav  a2 s . com*/
public void process(String sUserId, IAttributes oAttributes) throws AttributeException {
    DirContext oDirContext = null;
    NamingEnumeration oNamingEnumeration = null;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment);
            throw new AttributeException(SystemErrors.ERROR_RESOURCE_CONNECT, e);
        }

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);
        if (_listGather.size() > 0) {
            String[] saAttributes = _listGather.toArray(new String[0]);
            oScope.setReturningAttributes(saAttributes);
        }

        String searchFilter = resolveSearchQuery(sUserId);
        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope);
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Wrong filter: ");
            sbFailed.append(searchFilter);
            sbFailed.append(" while searching for attributes for id: ");
            sbFailed.append(sUserId);
            _logger.error(sbFailed.toString(), e);
            throw new AttributeException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        } catch (NamingException e) {
            _logger.debug("User unknown: " + sUserId);
            return;
        }

        if (oNamingEnumeration.hasMore()) {
            SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next();
            Attributes oSearchedAttributes = oSearchResult.getAttributes();
            NamingEnumeration neAttributes = oSearchedAttributes.getAll();
            while (neAttributes.hasMore()) {
                Attribute oAttribute = (Attribute) neAttributes.next();
                String sAttributeName = oAttribute.getID();
                String sMappedName = _htMapper.get(sAttributeName);
                if (sMappedName != null)
                    sAttributeName = sMappedName;

                if (oAttribute.size() > 1) {
                    Vector<Object> vValue = new Vector<Object>();
                    NamingEnumeration neAttribute = oAttribute.getAll();
                    while (neAttribute.hasMore())
                        vValue.add(neAttribute.next());

                    oAttributes.put(sAttributeName, vValue);
                } else {
                    Object oValue = oAttribute.get();
                    if (oValue == null)
                        oValue = "";
                    oAttributes.put(sAttributeName, oValue);
                }
            }
        }
    } catch (AttributeException e) {
        throw e;
    } catch (NamingException e) {
        _logger.debug("Failed to fetch attributes for user: " + sUserId, e);
    } catch (Exception e) {
        _logger.fatal("Could not retrieve fields for user with id: " + sUserId, e);
        throw new AttributeException(SystemErrors.ERROR_INTERNAL);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for user with id: " + sUserId,
                        e);
            }
        }
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after searching for user with id: " + sUserId, e);
            }
        }
    }
}

From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

/**
 * Attempts to authenticate user credentials with the LDAP server
 * /* w  ww . j a va  2s  . c om*/
 * @param username
 *            a username
 * @param password
 *            a password
 * @param dn
 *            if precise dn known, otherwise should be empty string
 * @return <code>true</code> if authentication was successful,
 *         <code>false</code> otherwise
 */
private boolean bind(String username, String password) {
    try {
        String principal = String.format("%s=%s,%s", idAttr, username, baseDn);
        env.put(Context.SECURITY_PRINCIPAL, principal);
        env.put(Context.SECURITY_CREDENTIALS, password);
        DirContext ctx = new InitialDirContext(env);
        ctx.lookup(principal);
        ctx.close();
        return true;
    } catch (NamingException ne) {
        log.warn("Failed LDAP lookup doAuthenticate", ne);
    }
    return false;
}