Example usage for javax.naming.ldap InitialLdapContext close

List of usage examples for javax.naming.ldap InitialLdapContext close

Introduction

In this page you can find the example usage for javax.naming.ldap InitialLdapContext close.

Prototype

public void close() throws NamingException 

Source Link

Usage

From source file:com.adito.activedirectory.ActiveDirectoryUserDatabase.java

protected static void close(InitialLdapContext context) {
    if (context != null) {
        try {//from   w  ww  .  j  a v  a 2 s .c o  m
            context.close();
        } catch (NamingException e) {
            // ignore
        }
    }
}

From source file:net.identio.server.service.authentication.ldap.LdapConnectionFactory.java

public boolean authenticate(String name, String dn, String password) {

    InitialLdapContext ctx = null;

    try {// www  .java 2s .  com
        ctx = createContext(ldapAuthMethod, dn, password);

        return true;
    } catch (NamingException e) {

        return false;
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                LOG.error("Error when closing connection to LDAP {}", ldapAuthMethod.getName());
            }
        }
    }
}

From source file:gda.jython.authenticator.LdapAuthenticator.java

private boolean checkAuthenticatedUsingServer(String ldapURL, String fedId, String password)
        throws NamingException {

    InitialLdapContext ctx = null;
    try {/*from w  ww .j a  v a 2s .  co m*/
        Hashtable<String, String> env = new Hashtable<String, String>();
        String principal = "CN=" + fedId + adminName;
        env.put(Context.INITIAL_CONTEXT_FACTORY, ldapContext);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, principal);
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put(Context.PROVIDER_URL, ldapURL);
        ctx = new InitialLdapContext(env, null);
        //if no exception then password is OK
        return true;
    } catch (AuthenticationException ae) {
        logger.error("LDAP AuthenticationException: " + StringEscapeUtils.escapeJava(ae.getMessage()));
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
            }
        }
    }
    return false;
}

From source file:de.fiz.ddb.aas.auxiliaryoperations.ThreadOrganisationCreate.java

private void createOrg() throws ExecutionException, IllegalArgumentException, AASUnauthorizedException {
    InitialLdapContext vCtx = null;

    Attributes vOrgAttributes = new BasicAttributes(true);

    BasicAttribute objectClass = new BasicAttribute("objectclass", "top");
    objectClass.add(Constants.ldap_ddbOrg_ObjectClass);
    objectClass.add("organization");

    vOrgAttributes.put(objectClass);/*from  w  w w . j  a v a 2  s  . com*/

    // ---All this occurs only if that is not a copy in the export directory
    if (!this.isAddToLicensedOrgs()) {

        // -- When creating the status always set on Pending:
        if (!this.isIngestingOperation()) {
            this._orgObj.setStatus(ConstEnumOrgStatus.pending);
            long vTimeStamp = new Date().getTime();
            this._orgObj.setModified(vTimeStamp);
            this._orgObj.setCreated(vTimeStamp);
        }

        if (this._performer != null) {
            this._orgObj.setModifiedBy(this._performer.getUid());
            this._orgObj.setCreatedBy(this._performer.getUid());
        }

        // -- Is null, if it was isIngestingOperation or isAddToLicensedOrgs 
        //    and therefore does not need to be additionally checked
        if (_submit != null) {
            GeoAdresse vGeoAdresse;
            try {
                vGeoAdresse = _submit.get(50, TimeUnit.SECONDS);
                if (vGeoAdresse.getRequestStatus() == GeoRequestStatus.OK) {
                    this._orgObj.getAddress().setLatitude(vGeoAdresse.getLatitude());
                    this._orgObj.getAddress().setLongitude(vGeoAdresse.getLongitude());
                    this._orgObj.getAddress().setLocationDisplayName(vGeoAdresse.getLocationDisplayName());
                } else {
                    LOG.log(Level.WARNING, "GeoRequestStatus: {0}, (organization id: {1})",
                            new Object[] { vGeoAdresse.getRequestStatus(), this._orgObj.getOIDs() });
                }
            } catch (InterruptedException ex) {
                LOG.log(Level.WARNING,
                        "Geocoding request exeption for organization id: " + this._orgObj.getOIDs(), ex);
            } catch (TimeoutException ex) {
                LOG.log(Level.WARNING,
                        "Geocoding request exeption for organization id: " + this._orgObj.getOIDs(), ex);
            }
        }
    }

    // -- Conversion of parameters to LDAP attributes:
    this.convertOrganizationToLdapOrgAttrsForCreate(this._orgObj, vOrgAttributes, getPerformer());

    StringBuilder vEntryDN = (this.isAddToLicensedOrgs() ? this.getLicensedOrgsDN(this._orgObj.getOIDs())
            : this.getOrgDN(this._orgObj.getOIDs()));

    try {
        // put arbitrary (Org) Properties as JSON-String into LDAP.
        if (this._orgObj.getProperties() != null && !this._orgObj.getProperties().isEmpty()) {
            vOrgAttributes.put(new BasicAttribute(Constants.ldap_ddbOrg_Properties,
                    serializer.serialize(this._orgObj.getProperties())));
        }

        // finally bind the entry
        vCtx = LDAPConnector.getSingletonInstance().takeCtx();
        ((InitialDirContext) vCtx).bind(vEntryDN.toString(), vCtx, vOrgAttributes);

        // -- Add default privilege(s) so we can assign performer
        //    but only if that is not a copy in the export directory
        if (!this.isAddToLicensedOrgs()) {
            this._orgObj.getPrivilegesSet().add(PrivilegeEnum.ADMIN_ORG);

            // create org-privileges
            for (PrivilegeEnum p : this._orgObj.getPrivilegesSet()) {
                ThreadSinglePrivilegeCreate threadSinglePrivilegeCreate = new ThreadSinglePrivilegeCreate(p,
                        this._orgObj, this._performer);
                threadSinglePrivilegeCreate.call();
            }
            // -- Logging:
            LOG.log(Level.INFO, "One organization with DN: ''{0}'' was created.", new Object[] { vEntryDN });
        } else {
            // -- Logging:
            LOG.log(Level.INFO, "One organization with DN: ''{0}'' was copied to the export directory.",
                    new Object[] { vEntryDN });
        }
    } catch (AssertionError ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw new IllegalArgumentException(ex.getMessage(), ex.getCause());
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NamingException ex) {
        // LDAP: error code 68 - ENTRY_ALREADY_EXISTS: failed for Add
        // Request
        try {
            if (vCtx != null) {
                vCtx.close();
                vCtx = null;
            }
        } catch (NamingException ex1) {
            LOG.log(Level.SEVERE, null, ex1);
        }
        try {
            vCtx = LDAPConnector.getSingletonInstance().getDirContext();
        } catch (NamingException ex1) {
            LOG.log(Level.SEVERE, null, ex1);
        } catch (IllegalAccessException ex1) {
            LOG.log(Level.SEVERE, null, ex1);
        }
        throw new IllegalArgumentException(ex.getMessage());
    } finally {
        if (vCtx != null) {
            try {
                LDAPConnector.getSingletonInstance().putCtx(vCtx);
            } catch (Exception ex) {
                LOG.log(Level.SEVERE, "Exception", ex);
            }
        }
    }

}

From source file:no.feide.moria.directory.backend.JNDIBackend.java

/**
 * Checks whether a user element exists, based on its username value.
 * @param username/* ww w  .j a  v  a 2 s. com*/
 *            User name.
 * @return <code>true</code> if the user can be looked up through JNDI,
 *         otherwise <code>false</code>.
 * @throws BackendException
 *             If there is a problem accessing the backend.
 */
public final boolean userExists(final String username) throws BackendException {

    // Sanity checks.
    if ((username == null) || (username.length() == 0))
        return false;

    // The search pattern.
    String pattern = usernameAttribute + '=' + username;

    // Go through all references.
    InitialLdapContext ldap = null;
    for (int i = 0; i < myReferences.length; i++) {
        String[] references = myReferences[i].getReferences();
        final String[] usernames = myReferences[i].getUsernames();
        final String[] passwords = myReferences[i].getPasswords();
        for (int j = 0; j < references.length; j++) {

            try {

                // Context for this reference.
                try {
                    ldap = connect(references[j]);
                } catch (NamingException e) {
                    // Connection failed, but we might have other sources.
                    log.logWarn("Unable to access the backend on '" + references[j]
                            + "' to verify existence of '" + username + "': " + e.getClass().getName(),
                            mySessionTicket, e);
                    continue;
                }

                // Anonymous search or not?
                ldap.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
                if ((usernames[j].length() == 0) && (passwords[j].length() > 0))
                    log.logWarn("Search username is empty but search password is not - possible index problem",
                            mySessionTicket);
                else if ((passwords[j].length() == 0) && (usernames[j].length() > 0))
                    log.logWarn("Search password is empty but search username is not - possible index problem",
                            mySessionTicket);
                else if ((passwords[j].length() == 0) && (usernames[j].length() == 0)) {
                    log.logDebug("Anonymous search for user element DN on " + references[j], mySessionTicket);
                    ldap.removeFromEnvironment(Context.SECURITY_AUTHENTICATION);
                } else
                    log.logDebug("Non-anonymous search to verify existence of '" + username + "' on "
                            + references[j], mySessionTicket);
                ldap.addToEnvironment(Context.SECURITY_PRINCIPAL, usernames[j]);
                ldap.addToEnvironment(Context.SECURITY_CREDENTIALS, passwords[j]);

                // Search this reference.
                if (ldapSearch(ldap, pattern) != null)
                    return true;

            } catch (NamingException e) {

                // Unable to connect, but we might have other sources.
                log.logWarn("Unable to access the backend on '" + references[j] + "' to verify existence of '"
                        + username + "': " + e.getClass().getName(), mySessionTicket, e);
                continue;

            } finally {

                // Close the LDAP connection.
                if (ldap != null) {
                    try {
                        ldap.close();
                    } catch (NamingException e) {
                        // Ignored.
                        log.logWarn("Unable to close the backend connection to '" + references[j] + "': "
                                + e.getClass().getName(), mySessionTicket, e);
                    }
                }
            }

        }
    }

    // Still no match.
    return false;

}

From source file:no.feide.moria.directory.backend.JNDIBackend.java

/**
 * Authenticates the user using the supplied credentials and retrieves the
 * requested attributes.//from www  .ja  v  a 2  s .c  o m
 * @param userCredentials
 *            User's credentials. Cannot be <code>null</code>.
 * @param attributeRequest
 *            Requested attributes.
 * @return The requested attributes (<code>String</code> names and
 *         <code>String[]</code> values), if they did exist in the
 *         external backend. Otherwise returns those attributes that could
 *         actually be read, this may be an empty <code>HashMap</code>.
 *         Returns an empty <code>HashMap</code> if
 *         <code>attributeRequest</code> is <code>null</code> or an
 *         empty array.
 * @throws AuthenticationFailedException
 *             If the authentication fails.
 * @throws BackendException
 *             If there is a problem accessing the backend.
 * @throws IllegalArgumentException
 *             If <code>userCredentials</code> is <code>null</code>.
 */
public final HashMap<String, String[]> authenticate(final Credentials userCredentials,
        final String[] attributeRequest) throws AuthenticationFailedException, BackendException {

    // Sanity check.
    if (userCredentials == null)
        throw new IllegalArgumentException("Credentials cannot be NULL");

    // Go through all references.
    for (int i = 0; i < myReferences.length; i++) {
        final String[] references = myReferences[i].getReferences();
        final String[] usernames = myReferences[i].getUsernames();
        final String[] passwords = myReferences[i].getPasswords();
        for (int j = 0; j < references.length; j++) {

            // For the benefit of the finally block below.
            InitialLdapContext ldap = null;

            try {

                // Context for this reference.
                try {
                    ldap = connect(references[j]);
                } catch (NamingException e) {
                    // Connection failed, but we might have other sources.
                    log.logWarn("Unable to access the backend on '" + references[j] + "': "
                            + e.getClass().getName(), mySessionTicket, e);
                    continue;
                }

                // Skip search phase if the reference(s) are explicit.
                String rdn = "";
                if (myReferences[i].isExplicitlyIndexed()) {

                    // Add the explicit reference; no search phase, no RDN.
                    ldap.addToEnvironment(Context.SECURITY_PRINCIPAL,
                            references[j].substring(references[j].lastIndexOf('/') + 1));

                } else {

                    // Anonymous search or not?
                    ldap.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
                    if ((usernames[j].length() == 0) && (passwords[j].length() > 0))
                        log.logWarn(
                                "Search username is empty but search password is not - possible index problem",
                                mySessionTicket);
                    else if ((passwords[j].length() == 0) && (usernames[j].length() > 0))
                        log.logWarn(
                                "Search password is empty but search username is not - possible index problem",
                                mySessionTicket);
                    else if ((passwords[j].length() == 0) && (usernames[j].length() == 0)) {
                        log.logDebug("Anonymous search for user element DN on " + references[j],
                                mySessionTicket);
                        ldap.removeFromEnvironment(Context.SECURITY_AUTHENTICATION);
                    } else
                        log.logDebug("Non-anonymous search for user element DN on " + references[j],
                                mySessionTicket);
                    ldap.addToEnvironment(Context.SECURITY_PRINCIPAL, usernames[j]);
                    ldap.addToEnvironment(Context.SECURITY_CREDENTIALS, passwords[j]);

                    // Search using the implicit reference.
                    String pattern = usernameAttribute + '=' + userCredentials.getUsername();
                    rdn = ldapSearch(ldap, pattern);
                    if (rdn == null) {

                        // No user element found. Try to guess the RDN.
                        rdn = userCredentials.getUsername();
                        rdn = guessedAttribute + '=' + rdn.substring(0, rdn.indexOf('@'));
                        log.logDebug("No subtree match for " + pattern + " on " + references[j]
                                + " - guessing on RDN " + rdn, mySessionTicket);

                    } else
                        log.logDebug("Matched " + pattern + " to " + rdn + ',' + ldap.getNameInNamespace(),
                                mySessionTicket);
                    ldap.addToEnvironment(Context.SECURITY_PRINCIPAL, rdn + ',' + ldap.getNameInNamespace());
                }

                // Authenticate and get attributes.
                ldap.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
                ldap.addToEnvironment(Context.SECURITY_CREDENTIALS, userCredentials.getPassword());
                try {
                    ldap.reconnect(null);
                    log.logDebug("Successfully authenticated " + userCredentials.getUsername() + " on "
                            + references[j], mySessionTicket);
                    return getAttributes(ldap, rdn, attributeRequest); // Success.
                } catch (AuthenticationException e) {

                    // Authentication failed, but we may have other
                    // references.
                    log.logDebug("Failed to authenticate user " + userCredentials.getUsername() + " on "
                            + references[j] + " - authentication failed", mySessionTicket);
                    continue;

                } catch (AuthenticationNotSupportedException e) {

                    // Password authentication not supported for the DN.
                    // We may still have other references.
                    log.logDebug("Failed to authenticate user " + userCredentials.getUsername() + " on "
                            + references[j] + " - authentication not supported", mySessionTicket);
                    continue;

                }

            } catch (ConfigurationException e) {
                throw new BackendException("Backend configuration problem with " + references[j], e);
            } catch (NamingException e) {
                throw new BackendException("Unable to access the backend on " + references[j], e);
            } finally {

                // Close the LDAP connection.
                if (ldap != null) {
                    try {
                        ldap.close();
                    } catch (NamingException e) {
                        // Ignored.
                        log.logWarn(
                                "Unable to close the backend connection to " + references[j] + " - ignoring",
                                mySessionTicket, e);
                    }
                }
            }

        }
    }

    // No user was found.
    throw new AuthenticationFailedException(
            "Failed to authenticate user " + userCredentials.getUsername() + " - no user found");

}

From source file:org.apache.lens.server.user.LDAPBackedDatabaseUserConfigLoader.java

/**
 * Find account by account name.// www .ja  v  a  2 s .  c  om
 *
 * @param accountName the account name
 * @return the search result
 * @throws NamingException the naming exception
 */
protected SearchResult findAccountByAccountName(String accountName) throws NamingException {
    String searchFilter = String.format(searchFilterPattern, accountName);
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    InitialLdapContext ctx = new InitialLdapContext(env, null);
    try {
        NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchControls);
        if (!results.hasMoreElements()) {
            throw new UserConfigLoaderException("LDAP Search returned no accounts");
        }
        SearchResult searchResult = results.nextElement();
        if (results.hasMoreElements()) {
            throw new UserConfigLoaderException("More than one account found in ldap search");
        }
        return searchResult;
    } finally {
        ctx.close();
    }
}

From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPBindIdentityStore.java

/**
 * This store performs a bind to the configured LDAP server and closes the connection immediately.
 * If the connection fails, an exception is thrown, otherwise this method returns silentrly
 *
 * @return true if the bind is successful
 *///from   w  w w  . ja  va  2  s . c o  m
public boolean bind(String username, String password, BindContext bindCtx) throws SSOAuthenticationException {

    String dn = null;

    try {

        // first try to retrieve the user using an known user
        dn = selectUserDN(username);
        if (dn == null || "".equals(dn)) {
            if (logger.isDebugEnabled())
                logger.debug("No DN found for user : " + username);
            return false;
        }
        logger.debug("user dn = " + dn);

        // Create context without binding!
        InitialLdapContext ctx = this.createLdapInitialContext(null, null);
        Control[] ldapControls = null;

        try {

            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);

            if (isPasswordPolicySupport()) {
                // Configure request control for password policy:
                ctx.reconnect(new Control[] { new BasicControl(PasswordPolicyResponseControl.CONTROL_OID) });
            } else {
                ctx.reconnect(new Control[] {});
            }

            // Get response controls from reconnect BEFORE dn search, or they're lost
            ldapControls = ctx.getResponseControls();

            // Bind to LDAP an check for authentication warning/errors reported in password policy control:
            if (validateBindWithSearch) {
                selectUserDN(ctx, username);

                // Perhaps controls are not send during reconnet, try to get them now
                if (ldapControls == null || ldapControls.length == 0)
                    ldapControls = ctx.getResponseControls();
            }

            if (logger.isTraceEnabled())
                logger.trace("LDAP Bind with user credentials succeeded");

        } catch (AuthenticationException e) {

            if (logger.isDebugEnabled())
                logger.debug("LDAP Bind Authentication error : " + e.getMessage(), e);

            return false;

        } finally {

            if (isPasswordPolicySupport()) {

                // If an exception occurred, controls are not retrieved yet
                if (ldapControls == null || ldapControls.length == 0)
                    ldapControls = ctx.getResponseControls();

                // Check password policy LDAP Control
                PasswordPolicyResponseControl ppolicyCtrl = decodePasswordPolicyControl(ldapControls);
                if (ppolicyCtrl != null)
                    addPasswordPolicyToBindCtx(ppolicyCtrl, bindCtx);

            }

            ctx.close();
        }

        return true;

    } catch (Exception e) {
        throw new SSOAuthenticationException(
                "Cannot bind as user : " + username + " [" + dn + "]" + e.getMessage(), e);
    }

}

From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java

/**
 * Obtains the roles for the given user.
 *
 * @param username the user name to fetch user data.
 * @return the list of roles to which the user is associated to.
 * @throws NamingException LDAP error obtaining roles fro the given user
 *//*from  w ww.  jav  a2 s  .  com*/
protected String[] selectRolesByUsername(String username) throws NamingException, NoSuchUserException {
    List userRoles = new ArrayList();

    InitialLdapContext ctx = createLdapInitialContext();

    String rolesCtxDN = getRolesCtxDN();

    // Search for any roles associated with the user
    if (rolesCtxDN != null) {

        // The attribute where user DN is stored in roles :
        String uidAttributeID = getUidAttributeID();
        if (uidAttributeID == null)
            uidAttributeID = "uniquemember";

        // The attribute that identifies the role name 
        String roleAttrName = getRoleAttributeID();
        if (roleAttrName == null)
            roleAttrName = "roles";

        String userDN;
        if ("UID".equals(getRoleMatchingMode())) {
            // Use User ID to match the role
            userDN = username;
        } else if ("PRINCIPAL".equals(getRoleMatchingMode())) {
            // Use User ID to match the role
            userDN = _principalUidAttributeID + "=" + username;
        } else {
            // Default behaviour: Match the role using the User DN, not just the username :
            userDN = selectUserDN(username);
        }

        if (logger.isDebugEnabled())
            logger.debug(
                    "Searching Roles for user '" + userDN + "' in Uid attribute name '" + uidAttributeID + "'");

        if (userDN == null)
            throw new NoSuchUserException(username);

        try {
            if (userDN.contains("\\")) {
                logger.debug("Escaping '\\' character");
                userDN = userDN.replace("\\", "\\\\\\");
            }

            NamingEnumeration answer = ctx.search(rolesCtxDN, "(&(" + uidAttributeID + "=" + userDN + "))",
                    getSearchControls());

            if (logger.isDebugEnabled())
                logger.debug("Search Name:  " + rolesCtxDN);

            if (logger.isDebugEnabled())
                logger.debug("Search Filter:  (&(" + uidAttributeID + "=" + userDN + "))");

            if (!answer.hasMore())
                logger.info("No roles found for user " + username);

            while (answer.hasMore()) {
                SearchResult sr = (SearchResult) answer.next();
                Attributes attrs = sr.getAttributes();
                Attribute roles = attrs.get(roleAttrName);
                for (int r = 0; r < roles.size(); r++) {
                    Object value = roles.get(r);
                    String roleName = null;
                    // The role attribute value is the role name
                    roleName = value.toString();

                    if (roleName != null) {
                        if (logger.isDebugEnabled())
                            logger.debug("Saving role '" + roleName + "' for user '" + username + "'");
                        userRoles.add(roleName);
                    }
                }
            }
        } catch (NamingException e) {
            if (logger.isDebugEnabled())
                logger.debug("Failed to locate roles", e);
        }
    }
    // Close the context to release the connection
    ctx.close();
    return (String[]) userRoles.toArray(new String[userRoles.size()]);
}

From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java

/**
 * Fetches the supplied user DN./*  ww  w.  ja  va 2 s.co m*/
 *
 * @param uid the user id
 * @return the user DN for the supplied uid
 * @throws NamingException LDAP error obtaining user information.
 */
protected String selectUserDN(String uid) throws NamingException {

    String dn = null;
    InitialLdapContext ctx = createLdapInitialContext();

    try {
        dn = selectUserDN(ctx, uid);
    } finally {
        // Close the context to release the connection
        ctx.close();
    }

    return dn;

}