Example usage for javax.naming Context SECURITY_PRINCIPAL

List of usage examples for javax.naming Context SECURITY_PRINCIPAL

Introduction

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

Prototype

String SECURITY_PRINCIPAL

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

Click Source Link

Document

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

Usage

From source file:org.andromda.timetracker.test.EJB3Container.java

private static Hashtable<String, String> getInitialContextProperties(String principal, String credential) {
    Hashtable<String, String> props = new Hashtable<String, String>();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.security.jndi.JndiLoginInitialContextFactory");
    props.put(Context.SECURITY_PRINCIPAL, principal);
    props.put(Context.SECURITY_CREDENTIALS, credential);
    return props;
}

From source file:org.rhq.enterprise.server.core.jaas.LdapLoginModule.java

/**
 * @see org.jboss.security.auth.spi.UsernamePasswordLoginModule#validatePassword(java.lang.String,java.lang.String)
 *//*www.  j a va  2s  .  c o  m*/
protected boolean validatePassword(String inputPassword, String expectedPassword) {
    // Load our LDAP specific properties
    Properties env = getProperties();

    // Load the BaseDN
    String baseDN = (String) options.get("BaseDN");
    if (baseDN == null) {
        // If the BaseDN is not specified, log an error and refuse the login attempt
        log.info("BaseDN is not set, refusing login");
        return false;
    }

    // Many LDAP servers allow bind's with an emtpy password. We will deny all requests with empty passwords
    if ((inputPassword == null) || inputPassword.equals("")) {
        log.debug("Empty password, refusing login");
        return false;
    }

    // Load the LoginProperty
    String loginProperty = (String) options.get("LoginProperty");
    if (loginProperty == null) {
        // Use the default
        loginProperty = "cn";
    }

    // Load any search filter
    String searchFilter = (String) options.get("Filter");

    // Find the user that is calling us
    String userName = getUsername();

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

    try {
        InitialLdapContext ctx = new InitialLdapContext(env, null);
        SearchControls searchControls = getSearchControls();

        // Add the search filter if specified.  This only allows for a single search filter.. i.e. foo=bar.
        String filter;
        if ((searchFilter != null) && (searchFilter.length() != 0)) {
            filter = "(&(" + loginProperty + "=" + userName + ")" + "(" + searchFilter + "))";
        } else {
            filter = "(" + loginProperty + "=" + userName + ")";
        }

        log.debug("Using LDAP filter=" + filter);

        // Loop through each configured base DN.  It may be useful
        // in the future to allow for a filter to be configured for
        // each BaseDN, but for now the filter will apply to all.
        String[] baseDNs = baseDN.split(BASEDN_DELIMITER);
        for (int x = 0; x < baseDNs.length; x++) {
            NamingEnumeration answer = ctx.search(baseDNs[x], filter, searchControls);
            boolean ldapApiNpeFound = false;
            if (!answer.hasMoreElements()) {//BZ:582471- ldap api bug
                log.debug("User " + userName + " not found for BaseDN " + baseDNs[x]);

                // Nothing found for this DN, move to the next one if we have one.
                continue;
            }

            // We use the first match
            SearchResult si = (SearchResult) answer.next();

            // Construct the UserDN
            String userDN = si.getName() + "," + baseDNs[x];

            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, inputPassword);
            ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");

            //if successful then verified that user and pw are valid ldap credentials
            ctx.reconnect(null);

            return true;
        }

        // If we try all the BaseDN's and have not found a match, return false
        return false;
    } catch (Exception e) {
        log.info("Failed to validate password: " + e.getMessage());
        return false;
    }
}

From source file:org.sonar.plugins.ldap.LdapContextFactory.java

private InitialDirContext createInitialDirContext(String principal, String credentials, boolean pooling)
        throws NamingException {
    final InitialLdapContext ctx;
    if (startTLS) {
        // Note that pooling is not enabled for such connections, because "Stop TLS" is not performed.
        Properties env = new Properties();
        env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
        env.put(Context.PROVIDER_URL, providerUrl);
        env.put(Context.REFERRAL, DEFAULT_REFERRAL);
        // At this point env should not contain properties SECURITY_AUTHENTICATION, SECURITY_PRINCIPAL and SECURITY_CREDENTIALS to avoid "bind" operation prior to StartTLS:
        ctx = new InitialLdapContext(env, null);
        // http://docs.oracle.com/javase/jndi/tutorial/ldap/ext/starttls.html
        StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
        try {// w w w  .j  a  v a 2s  .  c om
            tls.negotiate();
        } catch (IOException e) {
            NamingException ex = new NamingException("StartTLS failed");
            ex.initCause(e);
            throw ex;
        }
        // Explicitly initiate "bind" operation:
        ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, authentication);
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, principal);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials);
        ctx.reconnect(null);
    } else {
        ctx = new InitialLdapContext(getEnvironment(principal, credentials, pooling), null);
    }
    return ctx;
}

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

public boolean findUserByEmail(UserEdit edit, String email) {

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

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
 *///w  ww . ja va  2  s.c o  m
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:alpine.auth.LdapConnectionWrapper.java

/**
 * Creates a DirContext with the applications configuration settings.
 * @return a DirContext//w w  w  . j  av  a 2 s.  c  o  m
 * @throws NamingException if an exception is thrown
 * @since 1.4.0
 */
public DirContext createDirContext() throws NamingException {
    final Hashtable<String, String> env = new Hashtable<>();
    env.put(Context.SECURITY_PRINCIPAL, BIND_USERNAME);
    env.put(Context.SECURITY_CREDENTIALS, BIND_PASSWORD);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, LDAP_URL);
    if (IS_LDAP_SSLTLS) {
        env.put("java.naming.ldap.factory.socket", "alpine.crypto.RelaxedSSLSocketFactory");
    }
    return new InitialDirContext(env);
}

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

/**
 * DOCUMENT ME!/*from w ww .j a  v  a2s  . co  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.easy.ldap.LdapContextFactory.java

/**
 * @return/*from ww  w .  jav  a  2s.com*/
 */
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:org.apache.synapse.transport.jms.JMSSender.java

/**
 * Performs the actual sending of the JMS message
 *///from   w w  w  .  j  ava2s .  c o  m
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:info.jtrac.acegi.JtracLdapAuthenticationProvider.java

/**
 * displayName and mail are returned always, the map allows us to support
 * getting arbitrary properties in the future, hopefully
 *//* w  w  w.j a v  a  2  s . c  o  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");
}