Example usage for javax.naming Context SECURITY_CREDENTIALS

List of usage examples for javax.naming Context SECURITY_CREDENTIALS

Introduction

In this page you can find the example usage for javax.naming Context SECURITY_CREDENTIALS.

Prototype

String SECURITY_CREDENTIALS

To view the source code for javax.naming Context SECURITY_CREDENTIALS.

Click Source Link

Document

Constant that holds the name of the environment property for specifying the credentials of the principal for authenticating the caller to the service.

Usage

From source file:org.mule.providers.ldap.util.DSManager.java

/**
 * Sets the system context root to null.
 * //from  w  w w  . ja  v a2  s  . c o  m
 * @see junit.framework.TestCase#tearDown()
 */
public synchronized void stop() throws Exception {
    logger.debug("DS is stopping ...");

    if (!running) {
        logger.debug("stop() called while is not running");

        if (checkSocketNotConnected()) {
            return;
        } else {
            logger.debug("stop() forced");
        }
    }

    // super.tearDown();
    Hashtable env = new Hashtable();
    env.put(Context.PROVIDER_URL, "ou=system");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.directory.server.jndi.ServerContextFactory");
    env.putAll(new ShutdownConfiguration().toJndiEnvironment());
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "secret");

    try {
        new InitialContext(env);
    } catch (Exception e) {
        // ignored
        // dont remove try catch block!!
    }

    sysRoot = null;
    doDelete(configuration.getWorkingDirectory());
    configuration = new MutableServerStartupConfiguration();

    logger.debug("DS waiting for socket release ...");

    // wait for shutdown
    int i = 0;

    while (i < 20 && !checkSocketNotConnected()) {
        Thread.sleep(2000);
        i++;
        logger.debug("Try " + i);
    }

    if (!checkSocketNotConnected()) {
        throw new Exception("Shutdown of DS not successfull, server socket was not freed");
    }

    logger.debug("DS now stopped!");
    running = false;

}

From source file:org.openiam.idm.srvc.auth.spi.AbstractLoginModule.java

public LdapContext connect(String userName, String password, ManagedSysDto managedSys) throws NamingException {

    if (keystore != null && !keystore.isEmpty()) {
        System.setProperty("javax.net.ssl.trustStore", keystore);
        System.setProperty("javax.net.ssl.keyStorePassword", keystorePasswd);
    }/*from  w  ww  .  ja  va  2  s  . c  o  m*/

    if (managedSys == null) {
        log.debug("ManagedSys is null");
        return null;
    }

    String hostUrl = managedSys.getHostUrl();
    if (managedSys.getPort() > 0) {
        hostUrl = hostUrl + ":" + String.valueOf(managedSys.getPort());
    }

    log.debug("connect: Connecting to target system: " + managedSys.getId());
    log.debug("connect: Managed System object : " + managedSys);

    log.info(" directory login = " + managedSys.getUserId());
    log.info(" directory login passwrd= *****");
    log.info(" javax.net.ssl.trustStore= " + System.getProperty("javax.net.ssl.trustStore"));
    log.info(" javax.net.ssl.keyStorePassword= " + System.getProperty("javax.net.ssl.keyStorePassword"));

    Hashtable<String, String> envDC = new Hashtable();
    envDC.put(Context.PROVIDER_URL, hostUrl);
    envDC.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    envDC.put(Context.SECURITY_AUTHENTICATION, "simple"); // simple
    envDC.put(Context.SECURITY_PRINCIPAL, userName);
    envDC.put(Context.SECURITY_CREDENTIALS, password);

    // Connections Pool configuration
    envDC.put("com.sun.jndi.ldap.connect.pool", "true");
    // Here is an example of a command line that sets the maximum pool size to 20, the preferred pool size to 10, and the idle timeout to 5 minutes for pooled connections.
    envDC.put("com.sun.jndi.ldap.connect.pool.prefsize", "10");
    envDC.put("com.sun.jndi.ldap.connect.pool.maxsize", "20");
    envDC.put("com.sun.jndi.ldap.connect.pool.timeout", "300000");

    LdapContext ldapContext = null;
    try {
        ldapContext = (LdapContext) new LdapCtxFactory().getInitialContext((Hashtable) envDC);

    } catch (CommunicationException ce) {
        log.error("Throw communication exception.", ce);

    } catch (NamingException ne) {
        log.error(ne.toString(), ne);

    } catch (Throwable e) {
        log.error(e.toString(), e);
    }

    return ldapContext;
}

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  w  ww.  ja  va  2  s .  c  o  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:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java

/**
 * Setup environment.// w  w  w.  j  a  va 2  s  . c o m
 * @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:org.rhq.enterprise.server.core.CustomJaasDeploymentService.java

private void validateLdapOptions(Map<String, String> options) throws NamingException {
    Properties env = new Properties();

    String factory = options.get(Context.INITIAL_CONTEXT_FACTORY);
    if (factory == null) {
        throw new NamingException("No initial context factory");
    }//  w w  w  . j a  v  a  2s  . c o m

    String url = options.get(Context.PROVIDER_URL);
    if (url == null) {
        throw new NamingException("Naming provider url not set");
    }

    String protocol = options.get(Context.SECURITY_PROTOCOL);
    if ("ssl".equals(protocol)) {
        String ldapSocketFactory = env.getProperty("java.naming.ldap.factory.socket");
        if (ldapSocketFactory == null) {
            env.put("java.naming.ldap.factory.socket", UntrustedSSLSocketFactory.class.getName());
        }
        env.put(Context.SECURITY_PROTOCOL, "ssl");
    }

    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factory);
    env.setProperty(Context.PROVIDER_URL, url);

    // Load any information we may need to bind
    String bindDN = options.get("BindDN");
    String bindPW = options.get("BindPW");
    if ((bindDN != null) && (bindDN.length() != 0) && (bindPW != null) && (bindPW.length() != 0)) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        env.setProperty(Context.SECURITY_CREDENTIALS, bindPW);
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    }

    log.debug("Validating LDAP properties. Initializing context...");
    new InitialLdapContext(env, null).close();

    return;
}

From source file:org.sonatype.security.ldap.realms.DefaultLdapContextFactory.java

@VisibleForTesting
Hashtable<String, String> getSetupEnvironment(String username, final String password,
        final boolean systemContext) {
    Preconditions.checkNotNull(url, "No ldap URL specified (ldap://<hostname>:<port>)");

    if (username != null && principalSuffix != null) {
        username += principalSuffix;/*from w w  w  .  jav  a2s. c  om*/
    }

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

    if (additionalEnvironment != null) {
        env.putAll(additionalEnvironment);
    }

    // if the Authentication scheme is none, and this is not the system ctx we need to set the scheme to 'simple'
    if ("none".equals(authentication) && !systemContext) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
    } else {
        env.put(Context.SECURITY_AUTHENTICATION, authentication);
    }

    if (username != null) {
        env.put(Context.SECURITY_PRINCIPAL, username);
    }
    if (password != null) {
        env.put(Context.SECURITY_CREDENTIALS, password);
    }
    env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactoryClassName);
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.REFERRAL, referral);

    // Only pool connections for system contexts
    if (usePooling && username != null && systemContext) {
        // Enable connection pooling
        env.put(SUN_CONNECTION_POOLING_PROPERTY, "true");
        // Enable pooling for plain and ssl connections
        env.put(SUN_CONNECTION_POOLING_PROTOCOL_PROPERTY, "plain ssl");
    }

    if (log.isDebugEnabled()) {
        log.debug("Initializing LDAP context using URL [" + url + "] and username [" + systemUsername + "] "
                + "with pooling [" + (usePooling ? "enabled" : "disabled") + "]");
    }
    return env;
}

From source file:org.apache.axis2.transport.jms.JMSListener.java

/**
 * Initialize the defined connection factories, parsing the TransportIn
 * descriptions//from   w ww . jav a 2  s.  c om
 *
 * @param transprtIn The Axis2 Transport in for the JMS
 */
private void initializeConnectionFactories(TransportInDescription transprtIn) {
    // iterate through all defined connection factories
    Iterator conFacIter = transprtIn.getParameters().iterator();

    while (conFacIter.hasNext()) {

        Parameter param = (Parameter) conFacIter.next();
        JMSConnectionFactory jmsConFactory = new JMSConnectionFactory(param.getName());

        ParameterIncludeImpl pi = new ParameterIncludeImpl();
        try {
            pi.deserializeParameters((OMElement) param.getValue());
        } catch (AxisFault axisFault) {
            handleException(
                    "Error reading Parameters for JMS connection " + "factory" + jmsConFactory.getName(),
                    axisFault);
        }

        // read connection facotry properties
        Iterator params = pi.getParameters().iterator();

        while (params.hasNext()) {
            Parameter p = (Parameter) params.next();

            if (Context.INITIAL_CONTEXT_FACTORY.equals(p.getName())) {
                jmsConFactory.addProperty(Context.INITIAL_CONTEXT_FACTORY, (String) p.getValue());
            } else if (Context.PROVIDER_URL.equals(p.getName())) {
                jmsConFactory.addProperty(Context.PROVIDER_URL, (String) p.getValue());
            } else if (Context.SECURITY_PRINCIPAL.equals(p.getName())) {
                jmsConFactory.addProperty(Context.SECURITY_PRINCIPAL, (String) p.getValue());
            } else if (Context.SECURITY_CREDENTIALS.equals(p.getName())) {
                jmsConFactory.addProperty(Context.SECURITY_CREDENTIALS, (String) p.getValue());
            } else if (JMSConstants.CONFAC_JNDI_NAME_PARAM.equals(p.getName())) {
                jmsConFactory.setJndiName((String) p.getValue());
            } else if (JMSConstants.CONFAC_JNDI_NAME_USER.equals(p.getName())) {
                jmsConFactory.setJndiUser((String) p.getValue());
            } else if (JMSConstants.CONFAC_JNDI_NAME_PASS.equals(p.getName())) {
                jmsConFactory.setJndiPass((String) p.getValue());
            } else if (JMSConstants.DEST_PARAM.equals(p.getName())) {
                StringTokenizer st = new StringTokenizer((String) p.getValue(), " ,");
                while (st.hasMoreTokens()) {
                    jmsConFactory.addDestination(st.nextToken(), null);
                }
            }
        }

        // connect to the actual connection factory
        try {
            jmsConFactory.connect();
            connectionFactories.put(jmsConFactory.getName(), jmsConFactory);
        } catch (NamingException e) {
            handleException("Error connecting to JMS connection factory : " + jmsConFactory.getJndiName(), e);
        }
    }
}

From source file:org.openadaptor.auxil.connector.jndi.JNDIConnection.java

protected Properties getConnectionProperties(Properties customProperties, String contextFactory,
        String providerUrl, String authentication, String principal, String credentials) {
    Properties env = new Properties();
    if (customProperties != null) {
        env.putAll(customProperties);/*from  w  ww  . j ava2s .  co m*/
    }
    if (contextFactory != null) {
        env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
    }
    if (providerUrl != null) {
        env.put(Context.PROVIDER_URL, _providerUrl);
    }
    // Authentication details
    if (authentication != null) {
        env.put(Context.SECURITY_AUTHENTICATION, authentication);
    }
    if (principal != null) {
        env.put(Context.SECURITY_PRINCIPAL, principal);
    }
    if (credentials != null) {
        env.put(Context.SECURITY_CREDENTIALS, credentials);
    }
    return env;
}

From source file:org.mule.module.ldap.api.jndi.LDAPJNDIConnection.java

/**
 * @param dn//from  w w w .  j av a 2 s  .c o m
 * @param password
 * @return
 * @throws LDAPException
 */
private Hashtable<String, String> buildEnvironment(String dn, String password) throws LDAPException {
    Hashtable<String, String> env = new Hashtable<String, String>();

    env.put(Context.REFERRAL, getReferral());
    env.put(Context.SECURITY_AUTHENTICATION, getAuthentication());
    if (!isNoAuthentication()) {
        env.put(Context.SECURITY_PRINCIPAL, dn);
        env.put(Context.SECURITY_CREDENTIALS, password);
    }
    env.put(Context.INITIAL_CONTEXT_FACTORY, getInitialContextFactory());
    env.put(Context.PROVIDER_URL, getProviderUrl());

    if (isConnectionPoolEnabled()) {
        env.put(POOL_ENABLED_ENV_PARAM, "true");

        env.put(AUTHENTICATION_ENV_PARAM, getAuthentication());

        if (getMaxPoolConnections() > 0) {
            env.put(MAX_POOL_SIZE_ENV_PARAM, String.valueOf(getMaxPoolConnections()));
        }

        if (getInitialPoolSizeConnections() > 0) {
            env.put(INIT_POOL_SIZE_ENV_PARAM, String.valueOf(getInitialPoolSizeConnections()));
        }

        if (getPoolTimeout() > 0) {
            env.put(TIME_OUT_ENV_PARAM, String.valueOf(getPoolTimeout()));
        }
    } else {
        env.put(POOL_ENABLED_ENV_PARAM, "false");
    }

    if (extendedEnvironment != null && extendedEnvironment.size() > 0) {
        env.putAll(extendedEnvironment);
    }

    return env;

}

From source file:org.acegisecurity.ldap.DefaultInitialDirContextFactory.java

public DirContext newInitialDirContext(String username, String password) {
    Hashtable env = getEnvironment();

    // Don't pool connections for individual users
    if (!username.equals(managerDn)) {
        env.remove(CONNECTION_POOL_KEY);
    }/*from  w w w .j  a v  a2s  .  co  m*/

    env.put(Context.SECURITY_PRINCIPAL, username);
    env.put(Context.SECURITY_CREDENTIALS, password);

    return connect(env);
}