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.apache.synapse.config.xml.AbstractDBMediatorFactory.java

/**
 * Lookup the DataSource on JNDI using the specified properties
 * @param pool the toplevel 'pool' element that holds DataSource information
 * @param mediator the mediator to store properties for serialization
 * @return a DataSource looked up using specified properties
 *///from   ww  w .  j a  v a  2s . c om
private DataSource lookupDataSource(OMElement pool, AbstractDBMediator mediator) {

    Hashtable props = new Hashtable();
    // load the minimum required properties
    props.put(Context.INITIAL_CONTEXT_FACTORY, (getValue(pool, ICCLASS_Q)));
    props.put(Context.SECURITY_PRINCIPAL, getValue(pool, USER_Q));
    props.put(Context.SECURITY_CREDENTIALS, getValue(pool, PASS_Q));
    props.put(Context.PROVIDER_URL, getValue(pool, URL_Q));
    String dsName = getValue(pool, DSNAME_Q);

    //save loaded properties for later
    mediator.addDataSourceProperty(ICCLASS_Q, getValue(pool, ICCLASS_Q));
    mediator.addDataSourceProperty(DSNAME_Q, getValue(pool, DSNAME_Q));
    mediator.addDataSourceProperty(URL_Q, getValue(pool, URL_Q));
    mediator.addDataSourceProperty(USER_Q, getValue(pool, USER_Q));
    mediator.addDataSourceProperty(PASS_Q, getValue(pool, PASS_Q));

    try {
        Context ctx = new InitialContext(props);
        if (ctx != null) {
            Object ds = ctx.lookup(dsName);
            if (ds != null && ds instanceof DataSource) {
                return (DataSource) ds;
            } else {
                handleException("DataSource : " + dsName + " not found when looking up"
                        + " using JNDI properties : " + props);
            }
        } else {
            handleException("Error getting InitialContext using JNDI properties : " + props);
        }
    } catch (NamingException e) {
        handleException("Error looking up DataSource : " + dsName + " using JNDI properties : " + props, e);
    }
    return null;
}

From source file:com.duroty.application.files.actions.DownloadFileAction.java

/**
 * DOCUMENT ME!//www.  ja v a2s  .c  o  m
 *
 * @param request DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 */
protected Hashtable getContextProperties(HttpServletRequest request) {
    Hashtable props = (Hashtable) SessionManager.getObject(Constants.CONTEXT_PROPERTIES, request);

    if (props == null) {
        props = new Hashtable();

        props.put(Context.INITIAL_CONTEXT_FACTORY,
                Configuration.properties.getProperty(Configuration.JNDI_INITIAL_CONTEXT_FACTORY));
        props.put(Context.URL_PKG_PREFIXES,
                Configuration.properties.getProperty(Configuration.JNDI_URL_PKG_PREFIXES));
        props.put(Context.PROVIDER_URL, Configuration.properties.getProperty(Configuration.JNDI_PROVIDER_URL));

        Principal principal = request.getUserPrincipal();
        props.put(Context.SECURITY_PRINCIPAL, principal.getName());
        props.put(Context.SECURITY_CREDENTIALS, SessionManager.getObject(Constants.JAAS_PASSWORD, request));

        props.put(Context.SECURITY_PROTOCOL,
                Configuration.properties.getProperty(Configuration.SECURITY_PROTOCOL));

        SessionManager.setObject(Constants.CONTEXT_PROPERTIES, props, request);
    }

    return props;
}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPConnectionContext.java

/**
 * @param userDN Distinguished name of the user to be authenticated
 * @param password Password of the user to be authenticated
 * @return The LDAP connection context with logged in as the given user.
 * @throws NamingException If the user cannot be authenticated or connection issue occurs.
 *///from w w w.j ava 2s.  c  o  m
LdapContext getContextWithCredentials(String userDN, String password) throws NamingException {
    LdapContext context;

    //create a temp env for this particular authentication session by copying the original env
    Hashtable<String, String> tempEnv = new Hashtable<>();
    for (Map.Entry<String, String> entry : environment.entrySet()) {
        tempEnv.put(entry.getKey(), entry.getValue());
    }
    //replace connection name and password with the passed credentials to this method
    tempEnv.put(Context.SECURITY_PRINCIPAL, userDN);
    tempEnv.put(Context.SECURITY_CREDENTIALS, password);

    //replace environment properties with these credentials
    context = new InitialLdapContext(tempEnv, null);
    return (context);
}

From source file:org.apache.synapse.transport.jms.JMSSender.java

/**
 * Performs the actual sending of the JMS message
 *//*from w ww .j  ava2s . com*/
public void sendMessage(MessageContext msgCtx, String targetAddress, OutTransportInfo outTransportInfo)
        throws AxisFault {

    JMSConnectionFactory jmsConnectionFactory = null;
    Connection connection = null; // holds a one time connection if used
    JMSOutTransportInfo jmsOut = null;
    Session session = null;
    Destination destination = null;
    Destination replyDestination = null;

    try {
        if (targetAddress != null) {

            jmsOut = new JMSOutTransportInfo(targetAddress);
            // do we have a definition for a connection factory to use for this address?
            jmsConnectionFactory = getJMSConnectionFactory(jmsOut);

            if (jmsConnectionFactory != null) {
                // create new or get existing session to send to the destination from the CF
                session = jmsConnectionFactory.getSessionForDestination(JMSUtils.getDestination(targetAddress));

            } else {
                // digest the targetAddress and locate CF from the EPR
                jmsOut.loadConnectionFactoryFromProperies();
                try {
                    // create a one time connection and session to be used
                    Hashtable jndiProps = jmsOut.getProperties();
                    String user = (String) jndiProps.get(Context.SECURITY_PRINCIPAL);
                    String pass = (String) jndiProps.get(Context.SECURITY_CREDENTIALS);

                    QueueConnectionFactory qConFac = null;
                    TopicConnectionFactory tConFac = null;
                    ConnectionFactory conFac = null;

                    if (JMSConstants.DESTINATION_TYPE_QUEUE.equals(jmsOut.getDestinationType())) {
                        qConFac = (QueueConnectionFactory) jmsOut.getConnectionFactory();
                    } else if (JMSConstants.DESTINATION_TYPE_TOPIC.equals(jmsOut.getDestinationType())) {
                        tConFac = (TopicConnectionFactory) jmsOut.getConnectionFactory();
                    } else {
                        handleException(
                                "Unable to determine type of JMS " + "Connection Factory - i.e Queue/Topic");
                    }

                    if (user != null && pass != null) {
                        if (qConFac != null) {
                            connection = qConFac.createQueueConnection(user, pass);
                        } else if (tConFac != null) {
                            connection = tConFac.createTopicConnection(user, pass);
                        }
                    } else {
                        if (qConFac != null) {
                            connection = qConFac.createQueueConnection();
                        } else if (tConFac != null) {
                            connection = tConFac.createTopicConnection();
                        }
                    }

                    if (JMSConstants.DESTINATION_TYPE_QUEUE.equals(jmsOut.getDestinationType())) {
                        session = ((QueueConnection) connection).createQueueSession(false,
                                Session.AUTO_ACKNOWLEDGE);
                    } else if (JMSConstants.DESTINATION_TYPE_TOPIC.equals(jmsOut.getDestinationType())) {
                        session = ((TopicConnection) connection).createTopicSession(false,
                                Session.AUTO_ACKNOWLEDGE);
                    }

                } catch (JMSException e) {
                    handleException("Error creating a connection/session for : " + targetAddress);
                }
            }
            destination = jmsOut.getDestination();

        } else if (outTransportInfo != null && outTransportInfo instanceof JMSOutTransportInfo) {

            jmsOut = (JMSOutTransportInfo) outTransportInfo;
            jmsConnectionFactory = jmsOut.getJmsConnectionFactory();

            session = jmsConnectionFactory.getSessionForDestination(jmsOut.getDestination().toString());
            destination = jmsOut.getDestination();
        }

        String replyDestName = (String) msgCtx.getProperty(JMSConstants.JMS_REPLY_TO);
        if (replyDestName != null) {
            if (jmsConnectionFactory != null) {
                replyDestination = jmsConnectionFactory.getDestination(replyDestName);
            } else {
                replyDestination = jmsOut.getReplyDestination(replyDestName);
            }
        }

        // now we are going to use the JMS session, but if this was a session from a
        // defined JMS connection factory, we need to synchronize as sessions are not
        // thread safe
        synchronized (session) {

            // convert the axis message context into a JMS Message that we can send over JMS
            Message message = null;
            String correlationId = null;
            try {
                message = createJMSMessage(msgCtx, session);
            } catch (JMSException e) {
                handleException("Error creating a JMS message from the axis message context", e);
            }

            String destinationType = jmsOut.getDestinationType();

            // if the destination does not exist, see if we can create it
            destination = JMSUtils.createDestinationIfRequired(destination, destinationType, targetAddress,
                    session);

            // should we wait for a synchronous response on this same thread?
            boolean waitForResponse = waitForSynchronousResponse(msgCtx);

            // if this is a synchronous out-in, prepare to listen on the response destination
            if (waitForResponse) {
                replyDestination = JMSUtils.setReplyDestination(replyDestination, session, message);
            }

            // send the outgoing message over JMS to the destination selected
            JMSUtils.sendMessageToJMSDestination(session, destination, message);

            // if we are expecting a synchronous response back for the message sent out
            if (waitForResponse) {
                try {
                    connection.start();
                } catch (JMSException ignore) {
                }
                try {
                    correlationId = message.getJMSMessageID();
                } catch (JMSException ignore) {
                }
                waitForResponseAndProcess(session, replyDestination, msgCtx, correlationId);
            }
        }

    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException ignore) {
            }
        }
    }
}

From source file:org.easy.ldap.LdapContextFactory.java

/**
 * @return//from ww w.  jav  a 2 s  .  c o  m
 */
private Hashtable<String, String> getEnviroment() {
    Hashtable<String, String> properties = new Hashtable<String, String>();

    properties.put(Context.PROVIDER_URL, createProviderUrl(environment.getProperty(PropertyNames.DOMAIN_DN)));

    properties.put(Context.INITIAL_CONTEXT_FACTORY,
            environment.getProperty(PropertyNames.INITIAL_CONTEXT_FACTORY_CLASS));
    properties.put("com.sun.jndi.ldap.connect.pool",
            environment.getProperty(PropertyNames.USE_LDAP_CONNECT_POOL));
    properties.put(Context.SECURITY_AUTHENTICATION,
            environment.getProperty(PropertyNames.ADMIN_AUTHENTICATION_METHOD));
    properties.put(Context.SECURITY_PRINCIPAL, environment.getProperty(PropertyNames.ADMIN_PRINCIPAL));
    properties.put(Context.SECURITY_CREDENTIALS, environment.getProperty(PropertyNames.ADMIN_CREDENTIALS));

    return properties;
}

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

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

From source file:com.zabbix.gateway.JMXItemChecker.java

@Override
public JSONArray getValues() throws ZabbixException {
    JSONArray values = new JSONArray();

    try {/*from w ww  .  j  a va 2s. c  o m*/

        HashMap<String, Object> env = null;

        env = new HashMap<String, Object>();
        env.put(JMXConnector.CREDENTIALS, new String[] { username, password });

        if (protocol.equals("t3") || protocol.equals("t3s")) {
            env.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote");
            env.put(javax.naming.Context.SECURITY_PRINCIPAL, ((String[]) env.get(JMXConnector.CREDENTIALS))[0]);
            env.put(javax.naming.Context.SECURITY_CREDENTIALS,
                    ((String[]) env.get(JMXConnector.CREDENTIALS))[1]);
        }

        // Required by SSL
        if (protocol.equals("jmxs")) {
            env.put("com.sun.jndi.rmi.factory.socket", new SslRMIClientSocketFactory());
        }

        jmxc = ZabbixJMXConnectorFactory.connect(url, env);
        mbsc = jmxc.getMBeanServerConnection();

        for (String key : keys)
            values.put(getJSONValue(key));
    } catch (Exception e) {
        throw new ZabbixException(e);
    } finally {
        try {
            if (null != jmxc)
                jmxc.close();
        } catch (java.io.IOException exception) {
        }

        jmxc = null;
        mbsc = null;
    }

    return values;
}

From source file:org.pegadi.server.user.LDAPUserServerImpl.java

/**
 * Can probably be done more elegant too.
 *
 * @param userDN   real dn to the user./*from w w w  . ja v a2s .c  o  m*/
 * @param password the user's password
 * @return
 */
public boolean checkAuthentication(String userDN, String password) {
    if (password.trim().equals(""))
        return false;
    DirContext ctx2 = null;
    try {
        // See if the user authenticates.
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, url + "/" + ldapBaseDN);
        env.put(Context.SECURITY_AUTHENTICATION, auth);
        env.put(Context.SECURITY_PRINCIPAL, userDN);
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put("com.sun.jndi.ldap.connect.timeout", "10000");
        // Specify timeout to be 10 seconds, only on non SSL since SSL connections
        // break with a timeout.
        ctx2 = new InitialDirContext(env);
        log.info("Successfully logged in... " + userDN);
    } catch (Exception e) {
        log.error("Exception during login", e);
        return false;
    }

    finally {
        try {
            ctx2.close();
        } catch (NamingException ignore) {
        }
    }

    return true;
}

From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java

public boolean getUser(UserEdit edit) {

    if (!userExists(edit.getEid()))
        return false;

    env.put(Context.SECURITY_PRINCIPAL, "");
    env.put(Context.SECURITY_CREDENTIALS, "");
    String filter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(edit.getEid()) + "))";
    return getUserInf(edit, filter);
}

From source file:nl.nn.adapterframework.ldap.LdapFindMemberPipe.java

private boolean findMember(String host, int port, String dnSearchIn, boolean useSsl, String dnFind,
        boolean recursiveSearch) throws NamingException {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    String provUrl = retrieveUrl(host, port, dnSearchIn, useSsl);
    env.put(Context.PROVIDER_URL, provUrl);
    if (StringUtils.isNotEmpty(cf.getUsername())) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, cf.getUsername());
        env.put(Context.SECURITY_CREDENTIALS, cf.getPassword());
    } else {//from www  .ja v a  2  s . c  om
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    }
    DirContext ctx = null;
    try {
        try {
            ctx = new InitialDirContext(env);
        } catch (CommunicationException e) {
            log.info("Cannot create constructor for DirContext (" + e.getMessage()
                    + "], will try again with dummy SocketFactory");
            env.put("java.naming.ldap.factory.socket", DummySSLSocketFactory.class.getName());
            ctx = new InitialLdapContext(env, null);
        }
        Attribute attrs = ctx.getAttributes("").get("member");
        if (attrs != null) {
            boolean found = false;
            for (int i = 0; i < attrs.size() && !found; i++) {
                String dnFound = (String) attrs.get(i);
                if (dnFound.equalsIgnoreCase(dnFind)) {
                    found = true;
                } else {
                    if (recursiveSearch) {
                        found = findMember(host, port, dnFound, useSsl, dnFind, recursiveSearch);
                    }
                }
            }
            return found;
        }
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.warn("Exception closing DirContext", e);
            }
        }
    }
    return false;
}