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:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

private DirContext createBindUserDirContext(final String userDn, final Object password) throws NamingException {
    if (null != userBindDirContextCreator) {
        return userBindDirContextCreator.createBindUserDirContext(userDn, password);
    }/*from   ww  w .j a  va  2  s .co  m*/
    Hashtable environment = getEnvironment();
    environment.put(Context.SECURITY_PRINCIPAL, userDn);
    environment.put(Context.SECURITY_CREDENTIALS, password);
    return new InitialDirContext(environment);
}

From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java

/**
 * Creates the directory context configuration.
 * /*from w ww  . ja va2  s.co m*/
 * @param loginId
 *            the user principal ID to use when establishing the connection
 * @param loginPassword
 *            the password credentials to use when establishing the connection
 * @param isConnectionRetry
 *            if true, the alternate URL will be employed
 * @return Hashtable<String,String>
 */
protected Hashtable<String, String> getDirectoryContextEnvironment(String loginId, String loginPassword,
        boolean isConnectionRetry) {
    Hashtable<String, String> env = new Hashtable<String, String>();

    env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);

    if (!isConnectionRetry) {
        env.put(Context.PROVIDER_URL, connectionUrl);

    } else if (alternateUrl != null) {
        env.put(Context.PROVIDER_URL, alternateUrl);
    }
    if (loginId != null) {
        env.put(Context.SECURITY_PRINCIPAL, loginId);
    }
    if (loginPassword != null) {
        env.put(Context.SECURITY_CREDENTIALS, loginPassword);
    }
    if (securityAuthentication != null) {
        env.put(Context.SECURITY_AUTHENTICATION, securityAuthentication);
    }
    if (connectionProtocol != null) {
        env.put(Context.SECURITY_PROTOCOL, connectionProtocol);
    }
    if (referralStrategy != null) {
        env.put(Context.REFERRAL, referralStrategy);
    }
    if (connectionTimeout > 0) {
        env.put("com.sun.jndi.ldap.connect.timeout", connectionTimeout + "");
    }
    return env;
}

From source file:com.globalsight.everest.usermgr.UserLdapHelper.java

/**
 * Binds the user to the context./*from  ww w.  j ava2  s .  co m*/
 * 
 * 
 * @param context
 * @param dn
 * @param password
 * @throws NamingException
 */
static void bindUser(DirContext context, String dn, String password) throws NamingException {
    if (context != null) {
        context.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
        context.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
    }
}

From source file:com.adaptris.core.SharedComponentListTest.java

private JmsConnection createPtpConnection(String uniqueId) throws PasswordException {
    JmsConnection c = new JmsConnection();
    StandardJndiImplementation jndi = new StandardJndiImplementation();
    jndi.setJndiName("Connection_Factory_To_Lookup");
    KeyValuePairSet kvps = jndi.getJndiParams();
    kvps.addKeyValuePair(new KeyValuePair(Context.SECURITY_PRINCIPAL, "Administrator"));
    kvps.addKeyValuePair(new KeyValuePair(Context.SECURITY_CREDENTIALS, "Administrator"));
    kvps.addKeyValuePair(new KeyValuePair("com.sonicsw.jndi.mfcontext.domain", "Domain1"));
    kvps.addKeyValuePair(//from   w  ww .  j ava  2 s .  c om
            new KeyValuePair(Context.INITIAL_CONTEXT_FACTORY, "com.sonicsw.jndi.mfcontext.MFContextFactory"));
    jndi.getJndiParams().addKeyValuePair(new KeyValuePair(Context.PROVIDER_URL, "tcp://localhost:2506"));
    c.setVendorImplementation(jndi);
    if (!isEmpty(uniqueId)) {
        c.setUniqueId(uniqueId);
    }
    return c;
}

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

/**
 * Does a subtree search for an element given a pattern. Only the first
 * element found is considered, and all references are searched in order
 * until either a match is found or no more references are left to search.
 * @param ldap/*w ww . ja v  a2s.c  o  m*/
 *            A prepared LDAP context.
 * @param pattern
 *            The search pattern. Must not include the character '*' or the
 *            substring '\2a' to prevent possible LDAP exploits.
 * @return The element's relative DN, or <code>null</code> if none was
 *         found. <code>null</code> is also returned if the search pattern
 *         contains an illegal character or substring.
 * @throws BackendException
 *             If there was a problem accessing the backend. Typical causes
 *             include timeouts.
 */
private String ldapSearch(final InitialLdapContext ldap, final String pattern) throws BackendException {

    // Check pattern for illegal content.
    String[] illegals = { "*", "\\2a" };
    for (int i = 0; i < illegals.length; i++) {
        if (pattern.indexOf(illegals[i]) > -1)
            return null;
    }

    // The context provider URL, for later logging.
    String url = "unknown backend";

    // Start counting the (milli)seconds and prepare for timeouts.
    long searchStart = System.currentTimeMillis();
    JNDISearchInterruptor interruptTask = new JNDISearchInterruptor(ldap, mySessionTicket);
    NamingEnumeration results;
    try {

        // Remember the URL, for later logging.
        url = (String) ldap.getEnvironment().get(Context.PROVIDER_URL);
        interruptTask.setURL(url);

        // Start timeout interruptor and perform the search.
        Timer interruptTimer = new Timer();
        interruptTimer.schedule(interruptTask, (1000 * myTimeout));
        results = ldap.search("", pattern, new SearchControls(SearchControls.SUBTREE_SCOPE, 0, 1000 * myTimeout,
                new String[] {}, false, false));
        interruptTimer.cancel();
        if (!results.hasMore())
            return null;

    } catch (TimeLimitExceededException e) {

        // The search timed out.
        log.logWarn("Search on " + url + " for " + pattern + " timed out after ~"
                + (System.currentTimeMillis() - searchStart) + "ms", mySessionTicket);
        return null;

    } catch (SizeLimitExceededException e) {

        // The search returned too many results.
        log.logWarn("Search on " + url + " for " + pattern + " returned too many results", mySessionTicket);
        return null;

    } catch (NameNotFoundException e) {

        // Element not found. Possibly non-existing reference.
        log.logDebug("Could not find " + pattern + " on " + url, mySessionTicket); // Necessary?
        return null;

    } catch (AuthenticationException e) {

        // Search failed authentication; check non-anonymous search config.
        try {
            final String searchUser = (String) ldap.getEnvironment().get(Context.SECURITY_PRINCIPAL);
            final String errorMessage;
            if ((searchUser == null) || searchUser.equals(""))
                errorMessage = "Anonymous search failed authentication on " + url;
            else
                errorMessage = "Could not authenticate search user " + searchUser + " on " + url;
            log.logDebug(errorMessage, mySessionTicket);
            throw new BackendException(errorMessage, e);
        } catch (NamingException f) {

            // Should not happen!
            log.logCritical("Unable to read LDAP environment", mySessionTicket, f);
            throw new BackendException("Unable to read LDAP environment", f);

        }

    } catch (NamingException e) {

        // Did we interrupt the search ourselves?
        if (interruptTask.finished()) {
            final long elapsed = System.currentTimeMillis() - searchStart;
            log.logWarn("Search on " + url + " for " + pattern + " timed out after ~" + elapsed + "ms",
                    mySessionTicket);
            throw new BackendException("Search on " + url + " for " + pattern + " timed out after ~" + elapsed
                    + "ms; connection terminated");
        }

        // All other exceptions.
        log.logWarn("Search on " + url + " for " + pattern + " failed", mySessionTicket, e);
        return null;

    }

    // We just found at least one element. Did we get an ambigious result?
    SearchResult entry = null;
    try {
        entry = (SearchResult) results.next();
        String buffer = new String();
        while (results.hasMoreElements())
            buffer = buffer + ", " + ((SearchResult) results.next()).getName();
        if (!buffer.equals(""))
            log.logWarn("Search on " + url + " for " + pattern + " gave ambiguous result: [" + entry.getName()
                    + buffer + "]", mySessionTicket);
        // TODO: Throw BackendException, or a subclass, or just (as now)
        // pick the first and hope for the best?
        buffer = null;
    } catch (NamingException e) {
        throw new BackendException("Unable to read search results", e);
    }
    return entry.getName(); // Relative DN (to the reference).

}

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

/**
 * Creates an InitialLdapContext by logging into the configured Ldap Server using the provided
 * username and credential./*w w w  . j  av a  2  s.  co m*/
 *
 * @return the Initial Ldap Context to be used to perform searches, etc.
 * @throws NamingException LDAP binding error.
 */
protected InitialLdapContext createLdapInitialContext(String securityPrincipal, String securityCredential)
        throws NamingException {

    Properties env = new Properties();

    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, getInitialContextFactory());
    env.setProperty(Context.SECURITY_AUTHENTICATION, getSecurityAuthentication());
    env.setProperty(Context.PROVIDER_URL, getProviderUrl());
    env.setProperty(Context.SECURITY_PROTOCOL, (getSecurityProtocol() == null ? "" : getSecurityProtocol()));

    // Set defaults for key values if they are missing

    String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
    if (factoryName == null) {
        factoryName = "com.sun.jndi.ldap.LdapCtxFactory";
        env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName);
    }

    String authType = env.getProperty(Context.SECURITY_AUTHENTICATION);

    if (authType == null)
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");

    String protocol = env.getProperty(Context.SECURITY_PROTOCOL);
    String providerURL = getProviderUrl();
    // Use localhost if providerUrl not set
    if (providerURL == null) {
        providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389");
    } else {
        // In case user configured provided URL
        if (providerURL.startsWith("ldaps")) {
            protocol = "ssl";
            env.setProperty(Context.SECURITY_PROTOCOL, "ssl");
        }

    }

    env.setProperty(Context.PROVIDER_URL, providerURL);

    if (securityPrincipal != null && !"".equals(securityPrincipal))
        env.setProperty(Context.SECURITY_PRINCIPAL, securityPrincipal);

    if (securityCredential != null && !"".equals(securityCredential))
        env.put(Context.SECURITY_CREDENTIALS, securityCredential);

    // always follow referrals transparently
    env.put(Context.REFERRAL, "follow");

    // Logon into LDAP server
    if (logger.isDebugEnabled())
        logger.debug("Logging into LDAP server, env=" + env);

    InitialLdapContext ctx = new InitialLdapContext(env, null);

    if (logger.isDebugEnabled())
        logger.debug("Logged into LDAP server, " + ctx);

    return ctx;
}

From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java

private void doBind(final StudioProgressMonitor monitor) throws NamingException {
    if (context != null && isConnected) {
        // setup authentication methdod
        authMethod = AUTHMETHOD_NONE;/*from   ww  w  . ja  va2  s.  c om*/
        if (connection.getConnectionParameter()
                .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SIMPLE) {
            authMethod = AUTHMETHOD_SIMPLE;
        } else if (connection.getConnectionParameter()
                .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_DIGEST_MD5) {
            authMethod = AUTHMETHOD_DIGEST_MD5;
            saslRealm = connection.getConnectionParameter().getSaslRealm();
        } else if (connection.getConnectionParameter()
                .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_CRAM_MD5) {
            authMethod = AUTHMETHOD_CRAM_MD5;
        } else if (connection.getConnectionParameter()
                .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_GSSAPI) {
            authMethod = AUTHMETHOD_GSSAPI;
        }

        // No Authentication
        if (authMethod == AUTHMETHOD_NONE) {
            bindPrincipal = ""; //$NON-NLS-1$
            bindCredentials = ""; //$NON-NLS-1$
        } else {
            // setup credentials
            IAuthHandler authHandler = ConnectionCorePlugin.getDefault().getAuthHandler();
            if (authHandler == null) {
                NamingException namingException = new NamingException(Messages.model__no_auth_handler);
                monitor.reportError(Messages.model__no_auth_handler, namingException);
                throw namingException;
            }
            ICredentials credentials = authHandler.getCredentials(connection.getConnectionParameter());
            if (credentials == null) {
                CancelException cancelException = new CancelException();
                monitor.setCanceled(true);
                monitor.reportError(Messages.model__no_credentials, cancelException);
                throw cancelException;
            }
            if (credentials.getBindPrincipal() == null || credentials.getBindPassword() == null) {
                NamingException namingException = new NamingException(Messages.model__no_credentials);
                monitor.reportError(Messages.model__no_credentials, namingException);
                throw namingException;
            }
            bindPrincipal = credentials.getBindPrincipal();
            bindCredentials = credentials.getBindPassword();
        }

        InnerRunnable runnable = new InnerRunnable() {
            public void run() {
                try {
                    context.removeFromEnvironment(Context.SECURITY_AUTHENTICATION);
                    context.removeFromEnvironment(Context.SECURITY_PRINCIPAL);
                    context.removeFromEnvironment(Context.SECURITY_CREDENTIALS);
                    context.removeFromEnvironment(JAVA_NAMING_SECURITY_SASL_REALM);

                    context.addToEnvironment(Context.SECURITY_AUTHENTICATION, authMethod);

                    // SASL options
                    if (connection.getConnectionParameter()
                            .getAuthMethod() == AuthenticationMethod.SASL_CRAM_MD5
                            || connection.getConnectionParameter()
                                    .getAuthMethod() == AuthenticationMethod.SASL_DIGEST_MD5
                            || connection.getConnectionParameter()
                                    .getAuthMethod() == AuthenticationMethod.SASL_GSSAPI) {
                        // Request quality of protection
                        switch (connection.getConnectionParameter().getSaslQop()) {
                        case AUTH:
                            context.addToEnvironment(Sasl.QOP, SaslQoP.AUTH.getValue());
                            break;
                        case AUTH_INT:
                            context.addToEnvironment(Sasl.QOP, SaslQoP.AUTH_INT.getValue());
                            break;
                        case AUTH_CONF:
                            context.addToEnvironment(Sasl.QOP, SaslQoP.AUTH_CONF.getValue());
                            break;
                        }

                        // Request mutual authentication
                        if (connection.getConnectionParameter().isSaslMutualAuthentication()) {
                            context.addToEnvironment(Sasl.SERVER_AUTH, "true"); //$NON-NLS-1$
                        } else {
                            context.removeFromEnvironment(Sasl.SERVER_AUTH);
                        }

                        // Request cryptographic protection strength
                        switch (connection.getConnectionParameter().getSaslSecurityStrength()) {
                        case HIGH:
                            context.addToEnvironment(Sasl.STRENGTH, SaslSecurityStrength.HIGH.getValue());
                            break;
                        case MEDIUM:
                            context.addToEnvironment(Sasl.STRENGTH, SaslSecurityStrength.MEDIUM.getValue());
                            break;
                        case LOW:
                            context.addToEnvironment(Sasl.STRENGTH, SaslSecurityStrength.LOW.getValue());
                            break;
                        }
                    }

                    // Bind
                    if (connection.getConnectionParameter()
                            .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_GSSAPI) {
                        // GSSAPI
                        doGssapiBind(this);
                    } else {
                        // no GSSAPI
                        context.addToEnvironment(Context.SECURITY_PRINCIPAL, bindPrincipal);
                        context.addToEnvironment(Context.SECURITY_CREDENTIALS, bindCredentials);

                        if (connection.getConnectionParameter()
                                .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_DIGEST_MD5
                                && StringUtils.isNotEmpty(saslRealm)) {
                            context.addToEnvironment(JAVA_NAMING_SECURITY_SASL_REALM, saslRealm);
                        }

                        context.reconnect(context.getConnectControls());
                    }
                } catch (NamingException ne) {
                    namingException = ne;
                }
            }
        };

        runAndMonitor(runnable, monitor);

        if (runnable.getException() != null) {
            throw runnable.getException();
        } else if (context != null) {
            // all OK
        } else {
            throw new NamingException("???"); //$NON-NLS-1$
        }
    } else {
        throw new NamingException(NO_CONNECTION);
    }
}

From source file:org.liveSense.auth.ldap.LdapAuthenticationHandler.java

boolean isLdapValid(final Credentials credentials) throws RepositoryException {
    LdapUser ldapUser = getLdapAuthData(credentials);
    if (ldapUser != null) {
        Hashtable<String, String> authEnv = new Hashtable<String, String>(11);
        //String dn = "uid=" + ldapUser.getUserName() + "," + ldapBase;
        String dn = StringUtils.replace(ldapBase, "${userName}", ldapUser.getUserName());
        authEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        authEnv.put(Context.PROVIDER_URL, ldapUrl);
        authEnv.put(Context.SECURITY_AUTHENTICATION, ldapAuthenticationType);
        authEnv.put(Context.SECURITY_PRINCIPAL, dn);
        authEnv.put(Context.SECURITY_CREDENTIALS, ldapUser.getPassword());
        try {/* w  w  w.  j  a  va 2 s  . c o m*/
            DirContext ctx = new InitialDirContext(authEnv);
            Attributes attributes = ctx.getAttributes(dn);
            ldapUser.setAttributes(attributes);
            return true;
        } catch (AuthenticationException authEx) {
            return false;

        } catch (NamingException namEx) {
            throw new RepositoryException("Ldap Error:" + namEx.getExplanation());
        }
    }
    // no authdata, not valid
    return false;
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

/**
 * get the context for connection// w  w  w .ja v  a  2  s .  c  o m
 *
 * @return
 */
@SuppressWarnings("unchecked")
public Hashtable getEnvironment() {
    Properties env = new Properties();

    env.put(Context.INITIAL_CONTEXT_FACTORY, _contextFactory);
    String url = null;
    if (_providerUrl != null) {
        url = _providerUrl;
    } else {
        if (_hostname != null) {
            url = "ldap://" + _hostname + "/";
            if (_port != 0) {
                url += ":" + _port + "/";
            }

            LOG.warn("Using hostname and port.  Use providerUrl instead: " + url);
        }
    }
    env.put(Context.PROVIDER_URL, url);

    if (_authenticationMethod != null) {
        env.put(Context.SECURITY_AUTHENTICATION, _authenticationMethod);
    }

    if (_bindDn != null) {
        env.put(Context.SECURITY_PRINCIPAL, _bindDn);
    }

    if (_bindPassword != null) {
        env.put(Context.SECURITY_CREDENTIALS, _bindPassword);
    }
    env.put("com.sun.jndi.ldap.read.timeout", Long.toString(_timeoutRead));
    env.put("com.sun.jndi.ldap.connect.timeout", Long.toString(_timeoutConnect));

    // Set the SSLContextFactory to implementation that validates cert subject
    if (url != null && url.startsWith("ldaps") && _ldapsVerifyHostname) {
        try {
            URI uri = new URI(url);
            HostnameVerifyingSSLSocketFactory.setTargetHost(uri.getHost());
            env.put("java.naming.ldap.factory.socket",
                    "com.dtolabs.rundeck.jetty.jaas.HostnameVerifyingSSLSocketFactory");
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    return env;
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java

@Override
public boolean authenticate(String username, String password) throws DirectoryException {

    if (password == null || "".equals(password.trim())) {
        // never use anonymous bind as a way to authenticate a user in
        // Nuxeo EP
        return false;
    }/*from w  ww .  j  av a  2 s. c o  m*/

    // lookup the user: fetch its dn
    SearchResult entry;
    try {
        entry = getLdapEntry(username);
    } catch (NamingException e) {
        throw new DirectoryException("failed to fetch the ldap entry for " + username, e);
    }
    if (entry == null) {
        // no such user => authentication failed
        return false;
    }
    String dn = entry.getNameInNamespace();
    Properties env = (Properties) getDirectory().getContextProperties().clone();
    env.put(Context.SECURITY_PRINCIPAL, dn);
    env.put(Context.SECURITY_CREDENTIALS, password);

    InitialLdapContext authenticationDirContext = null;
    try {
        // creating a context does a bind
        log.debug(String.format("LDAP bind dn='%s'", dn));
        // noinspection ResultOfObjectAllocationIgnored
        authenticationDirContext = new InitialLdapContext(env, null);
        // force reconnection to prevent from using a previous connection
        // with an obsolete password (after an user has changed his
        // password)
        authenticationDirContext.reconnect(null);
        log.debug("Bind succeeded, authentication ok");
        return true;
    } catch (NamingException e) {
        log.debug("Bind failed: " + e.getMessage());
        // authentication failed
        return false;
    } finally {
        try {
            if (authenticationDirContext != null) {
                authenticationDirContext.close();
            }
        } catch (NamingException e) {
            log.error("Error closing authentication context when biding dn " + dn, e);
            return false;
        }
    }
}