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.wso2.carbon.user.core.ldap.LDAPConnectionContext.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public LDAPConnectionContext(RealmConfiguration realmConfig) throws UserStoreException {

    //if DNS is enabled, populate DC Map
    String DNSUrl = realmConfig.getUserStoreProperty(LDAPConstants.DNS_URL);
    if (DNSUrl != null) {
        DNSDomainName = realmConfig.getUserStoreProperty(LDAPConstants.DNS_DOMAIN_NAME);
        if (DNSDomainName == null) {
            throw new UserStoreException("DNS is enabled, but DNS domain name not provided.");
        } else {/* w  ww.  j a  va2s  . c  o m*/
            environmentForDNS = new Hashtable();
            environmentForDNS.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
            environmentForDNS.put("java.naming.provider.url", DNSUrl);
            populateDCMap();
        }
        //need to keep track of if the user store config is read only
        String readOnlyString = realmConfig
                .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_READ_ONLY);
        if (readOnlyString != null) {
            readOnly = Boolean.parseBoolean(readOnlyString);
        }
    }

    String rawConnectionURL = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_URL);
    String connectionURL = null;
    //if DNS enabled in AD case, this can be null
    if (rawConnectionURL != null) {
        String portInfo = rawConnectionURL.split(":")[2];

        String port = null;

        // if the port contains a template string that refers to carbon.xml
        if ((portInfo.contains("${")) && (portInfo.contains("}"))) {
            port = Integer.toString(CarbonUtils.getPortFromServerConfig(portInfo));
        }

        if (port != null) {
            connectionURL = rawConnectionURL.replace(portInfo, port);
        } else {
            // if embedded-ldap is not enabled,
            connectionURL = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_URL);
        }
    }

    String connectionName = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_NAME);
    String connectionPassword = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_PASSWORD);

    if (log.isDebugEnabled()) {
        log.debug("Connection Name :: " + connectionName + ", Connection URL :: " + connectionURL);
    }

    environment = new Hashtable();

    environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environment.put(Context.SECURITY_AUTHENTICATION, "simple");

    /**
     * In carbon JNDI context we need to by pass specific tenant context and we need the base
     * context for LDAP operations.
     */
    environment.put(CarbonConstants.REQUEST_BASE_CONTEXT, "true");

    if (connectionName != null) {
        environment.put(Context.SECURITY_PRINCIPAL, connectionName);
    }

    if (connectionPassword != null) {
        environment.put(Context.SECURITY_CREDENTIALS, connectionPassword);
    }

    if (connectionURL != null) {
        environment.put(Context.PROVIDER_URL, connectionURL);
    }

    // Enable connection pooling if property is set in user-mgt.xml
    boolean isLDAPConnectionPoolingEnabled = false;
    String value = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_POOLING_ENABLED);

    if (value != null && !value.trim().isEmpty()) {
        isLDAPConnectionPoolingEnabled = Boolean.parseBoolean(value);
    }

    environment.put("com.sun.jndi.ldap.connect.pool", isLDAPConnectionPoolingEnabled ? "true" : "false");

    // set referral status if provided in configuration.
    if (realmConfig.getUserStoreProperty(LDAPConstants.PROPERTY_REFERRAL) != null) {
        environment.put("java.naming.referral",
                realmConfig.getUserStoreProperty(LDAPConstants.PROPERTY_REFERRAL));
    }

    String binaryAttribute = realmConfig.getUserStoreProperty(LDAPConstants.LDAP_ATTRIBUTES_BINARY);

    if (binaryAttribute != null) {
        environment.put(LDAPConstants.LDAP_ATTRIBUTES_BINARY, binaryAttribute);
    }

    //Set connect timeout if provided in configuration. Otherwise set default value
    String connectTimeout = realmConfig.getUserStoreProperty(CONNECTION_TIME_OUT);
    if (connectTimeout != null && !connectTimeout.trim().isEmpty()) {
        environment.put("com.sun.jndi.ldap.connect.timeout", connectTimeout);
    } else {
        environment.put("com.sun.jndi.ldap.connect.timeout", "5000");
    }
}

From source file:nl.nn.adapterframework.jms.JNDIBase.java

protected Hashtable getJndiEnv() throws NamingException {
    Properties jndiEnv = new Properties();

    if (StringUtils.isNotEmpty(getJndiProperties())) {
        URL url = ClassUtils.getResourceURL(classLoader, getJndiProperties());
        if (url == null) {
            throw new NamingException("cannot find jndiProperties from [" + getJndiProperties() + "]");
        }//from w w w .  ja  v a  2 s  .co  m
        try {
            jndiEnv.load(url.openStream());
        } catch (IOException e) {
            throw new NamingException("cannot load jndiProperties [" + getJndiProperties() + "] from url ["
                    + url.toString() + "]");
        }
    }
    if (getInitialContextFactoryName() != null)
        jndiEnv.put(Context.INITIAL_CONTEXT_FACTORY, getInitialContextFactoryName());
    if (getProviderURL() != null)
        jndiEnv.put(Context.PROVIDER_URL, getProviderURL());
    if (getAuthentication() != null)
        jndiEnv.put(Context.SECURITY_AUTHENTICATION, getAuthentication());
    if (getPrincipal() != null || getCredentials() != null || getJndiAuthAlias() != null) {
        CredentialFactory jndiCf = new CredentialFactory(getJndiAuthAlias(), getPrincipal(), getCredentials());
        if (StringUtils.isNotEmpty(jndiCf.getUsername()))
            jndiEnv.put(Context.SECURITY_PRINCIPAL, jndiCf.getUsername());
        if (StringUtils.isNotEmpty(jndiCf.getPassword()))
            jndiEnv.put(Context.SECURITY_CREDENTIALS, jndiCf.getPassword());
    }
    if (getUrlPkgPrefixes() != null)
        jndiEnv.put(Context.URL_PKG_PREFIXES, getUrlPkgPrefixes());
    if (getSecurityProtocol() != null)
        jndiEnv.put(Context.SECURITY_PROTOCOL, getSecurityProtocol());

    if (log.isDebugEnabled()) {
        for (Iterator it = jndiEnv.keySet().iterator(); it.hasNext();) {
            String key = (String) it.next();
            String value = jndiEnv.getProperty(key);
            log.debug("jndiEnv [" + key + "] = [" + value + "]");
        }
    }
    return jndiEnv;
}

From source file:org.kitodo.production.services.data.LdapServerService.java

private Hashtable<String, String> initializeWithLdapConnectionSettings(LdapServer ldapServer) {
    Hashtable<String, String> env = new Hashtable<>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapServer.getUrl());
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, ldapServer.getManagerLogin());

    String encryptedManagerPassword = ldapServer.getManagerPassword();
    String decryptedManagerPassword = passwordEncoder.decrypt(encryptedManagerPassword);

    env.put(Context.SECURITY_CREDENTIALS, decryptedManagerPassword);

    if (ldapServer.isUseSsl()) {
        String keystorepath = ldapServer.getKeystore();
        String keystorepasswd = ldapServer.getKeystorePassword();

        // add all necessary certificates first
        loadCertificates(keystorepath, keystorepasswd, ldapServer);

        // set properties, so that the current keystore is used for SSL
        System.setProperty("javax.net.ssl.keyStore", keystorepath);
        System.setProperty("javax.net.ssl.trustStore", keystorepath);
        System.setProperty("javax.net.ssl.keyStorePassword", keystorepasswd);
        env.put(Context.SECURITY_PROTOCOL, "ssl");
    }/*from   www  . j a va  2s .  com*/
    return env;
}

From source file:org.picketlink.idm.performance.TestBase.java

public LdapContext getLdapContext() throws Exception {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, LDAP_PROVIDER_URL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, LDAP_PRINCIPAL);
    env.put(Context.SECURITY_CREDENTIALS, LDAP_CREDENTIALS);

    return new InitialLdapContext(env, null);
}

From source file:com.hs.mail.security.login.JndiLoginModule.java

@SuppressWarnings("unchecked")
protected DirContext open() throws NamingException {
    if (context == null) {
        try {/*from   w  ww .ja v  a  2  s. c om*/
            // Set up the environment for creating the initial context
            Hashtable env = new Hashtable();
            env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
            if (StringUtils.isNotEmpty(username)) {
                env.put(Context.SECURITY_PRINCIPAL, username);
            }
            if (StringUtils.isNotEmpty(password)) {
                env.put(Context.SECURITY_CREDENTIALS, password);
            }
            env.put(Context.PROVIDER_URL, url);
            env.put(Context.SECURITY_AUTHENTICATION, authentication);
            context = new InitialDirContext(env);
        } catch (NamingException e) {
            throw e;
        }
    }
    return context;
}

From source file:org.dcm4che3.tool.dcmldap.DcmLdap.java

private static Hashtable<?, ?> ldapEnv(CommandLine cl) {
    Hashtable<String, Object> env = new Hashtable<>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put("java.naming.ldap.attributes.binary", "dicomVendorData");
    env.put(Context.PROVIDER_URL, cl.getOptionValue("H", DEFAULT_LDAP_URI));
    env.put(Context.SECURITY_PRINCIPAL, cl.getOptionValue("D", DEFAULT_BIND_DN));
    env.put(Context.SECURITY_CREDENTIALS, cl.getOptionValue("w", DEFAULT_PASSWORD));
    return env;/*  ww  w  .  j  a v  a2  s .  c o  m*/
}

From source file:org.exoplatform.services.organization.DummyLDAPServiceImpl.java

public DummyLDAPServiceImpl() throws Exception {
    File workingDirectory = new File("target/working-server");
    workingDirectory.mkdirs();/*from  w  ww  . j a v  a2 s  . c o m*/

    doDelete(workingDirectory);

    // Initialize the LDAP service
    service = new DefaultDirectoryService();
    service.setWorkingDirectory(workingDirectory);

    // first load the schema
    initSchemaPartition();

    // then the system partition
    // this is a MANDATORY partition
    Partition systemPartition = addPartition("system", ServerDNConstants.SYSTEM_DN);
    service.setSystemPartition(systemPartition);

    // Disable the ChangeLog system
    service.getChangeLog().setEnabled(false);

    // Create a new partition
    Partition partition = addPartition("eXoTestPartition", "dc=exoplatform,dc=org");

    // Index some attributes on the partition
    addIndex(partition, "objectClass", "ou", "uid");

    service.setShutdownHookEnabled(false);

    service.startup();

    // Inject the eXo root entry if it does not already exist
    if (!service.getAdminSession().exists(partition.getSuffixDn())) {
        DN dnExo = new DN("dc=exoplatform,dc=org");
        ServerEntry entryExo = service.newEntry(dnExo);
        entryExo.add("objectClass", "top", "domain", "extensibleObject");
        entryExo.add("dc", "exoplatform");
        service.getAdminSession().add(entryExo);
    }

    port = AvailablePortFinder.getNextAvailable(1024);
    server = new LdapServer();
    server.setTransports(new TcpTransport(port));
    server.setDirectoryService(service);
    server.start();

    // server launched and configured

    // configuration of client side
    env.put(DirectoryService.JNDI_KEY, service);
    env.put(Context.PROVIDER_URL, "");
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());

    // Add the new schema needed for COR-293
    addNewSchema();
}

From source file:org.gbif.portal.registration.LDAPUtils.java

/**
 * Get LDAP context.//from ww  w  .  j a v a  2  s  .  c  o m
 * @param url
 * @return
 * @throws NamingException
 */
public DirContext getContext(String url) throws NamingException {
    Hashtable env = new Hashtable();
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
    env.put(Context.SECURITY_AUTHENTICATION, authenticationType);
    env.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, securityCredentials);
    DirContext ctx = new InitialDirContext(env);
    return ctx;
}

From source file:org.apache.roller.weblogger.ui.rendering.plugins.comments.LdapCommentAuthenticator.java

public boolean authenticate(HttpServletRequest request) {
    boolean validUser = false;
    LdapContext context = null;//from   ww w. j  a va 2 s  .  c o m

    String ldapDc = WebloggerConfig.getProperty("comment.authenticator.ldap.dc");
    String ldapOu = WebloggerConfig.getProperty("comment.authenticator.ldap.ou");
    String ldapPort = WebloggerConfig.getProperty("comment.authenticator.ldap.port");
    String ldapHost = WebloggerConfig.getProperty("comment.authenticator.ldap.host");
    String ldapSecurityLevel = WebloggerConfig.getProperty("comment.authenticator.ldap.securityLevel");

    boolean rollerPropertiesValid = validateRollerProperties(ldapDc, ldapOu, ldapPort, ldapHost);

    String ldapUser = request.getParameter("ldapUser");
    String ldapPass = request.getParameter("ldapPass");

    boolean userDataValid = validateUsernamePass(ldapUser, ldapPass);

    if (rollerPropertiesValid && userDataValid) {
        try {
            Hashtable<String, String> env = new Hashtable<String, String>();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            if (ldapSecurityLevel != null && (ldapSecurityLevel.equalsIgnoreCase("none")
                    || ldapSecurityLevel.equalsIgnoreCase("simple")
                    || ldapSecurityLevel.equalsIgnoreCase("strong"))) {
                env.put(Context.SECURITY_AUTHENTICATION, ldapSecurityLevel);
            }
            env.put(Context.SECURITY_PRINCIPAL, getQualifedDc(ldapDc, ldapOu, ldapUser));
            env.put(Context.SECURITY_CREDENTIALS, ldapPass);
            env.put(Context.PROVIDER_URL, "ldap://" + ldapHost + ":" + ldapPort);
            context = new InitialLdapContext(env, null);
            validUser = true;
            LOG.info("LDAP Authentication Successful. user: " + ldapUser);
        } catch (Exception e) {
            // unexpected
            LOG.error(e);
        } finally {
            if (context != null) {
                try {
                    context.close();
                } catch (NamingException e) {
                    LOG.error(e);
                }
            }
        }
    }
    return validUser;
}

From source file:com.konakart.bl.LDAPMgrCore.java

/**
 * Called if the LDAP module is installed and active. This method should return:
 * <ul>/*w w  w.  ja va  2 s. co  m*/
 * <li>A negative number in order for the login attempt to fail. The KonaKart login() method
 * will return a null sessionId</li>
 * <li>Zero to signal that this method is not implemented. The KonaKart login() method will
 * perform the credential check.</li>
 * <li>A positive number for the login attempt to pass. The KonaKart login() will not check
 * credentials, and will log in the customer, returning a valid session id.</li>
 * </ul>
 * This method may need to be modified slightly depending on the structure of your LDAP. The
 * example works when importing the exampleData.ldif file in the LDAP module jar:
 * 
 * dn: cn=Robert Smith,ou=people,dc=example,dc=com<br/>
 * objectclass: inetOrgPerson<br/>
 * cn: Robert Smith<br/>
 * cn: Robert J Smith<br/>
 * cn: bob smith<br/>
 * sn: smith<br/>
 * uid: rjsmith<br/>
 * userpassword: rJsmitH<br/>
 * carlicense: HISCAR 123<br/>
 * homephone: 555-111-2222<br/>
 * mail: r.smith@example.com<br/>
 * mail: rsmith@example.com<br/>
 * mail: bob.smith@example.com<br/>
 * description: swell guy<br/>
 * 
 * The code attempts to connect to LDAP using the username, password and URL in the
 * configuration variables set when the module was installed through the admin app.<br/>
 * 
 * After having connected, the person object is searched for using the email address of the
 * user. If found we use the "cn" attribute and the password of the user to attempt to bind to
 * LDAP. If the bind is successful, we return a positive number which means that authentication
 * was successful.
 * 
 * @param emailAddr
 *            The user name required to log in
 * @param password
 *            The log in password
 * @return Returns an integer
 * @throws Exception
 */
public int checkCredentials(String emailAddr, String password) throws Exception {
    DirContext ctx = null;

    try {
        Hashtable<String, String> environment = new Hashtable<String, String>();

        if (log.isDebugEnabled()) {
            log.debug("LDAP connection URL                          =   " + url);
            log.debug("LDAP user name                               =   " + ldapUserName);
            log.debug("LDAP person object distinguished name (DN)   =   " + personDN);
        }

        if (ldapUserName == null) {
            throw new KKException(
                    "Cannot access LDAP because the MODULE_OTHER_LDAP_USER_NAME configuration variable hasn't been set.");
        }
        if (ldapPassword == null) {
            throw new KKException(
                    "Cannot access LDAP because the MODULE_OTHER_LDAP_PASSWORD configuration variable hasn't been set.");
        }
        if (url == null) {
            throw new KKException(
                    "Cannot access LDAP because the MODULE_OTHER_LDAP_URL configuration variable hasn't been set.");
        }
        if (personDN == null) {
            throw new KKException(
                    "Cannot validate through LDAP because the MODULE_OTHER_LDAP_PERSON_DN (Distinguished Name of Person Object) configuration variable hasn't been set.");
        }

        environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        environment.put(Context.SECURITY_AUTHENTICATION, "simple");
        environment.put(Context.PROVIDER_URL, url);
        environment.put(Context.SECURITY_PRINCIPAL, ldapUserName);
        environment.put(Context.SECURITY_CREDENTIALS, ldapPassword);

        /*
         * connect to LDAP using the credentials and connection string from the configuration
         * variables
         */
        try {
            ctx = new InitialDirContext(environment);
        } catch (Exception e) {
            log.error("Cannot connect to LDAP", e);
            return -1;
        }

        /* Specify the search filter on the eMail address */
        String filter = "(mail=" + emailAddr + ")";

        /*
         * limit returned attributes to those we care about. In this case we only require the
         * "cn" attribute which we will use to attempt to bind the user in order to validate his
         * password
         */
        String[] attrIDs = { "cn" };
        SearchControls ctls = new SearchControls();
        ctls.setReturningAttributes(attrIDs);
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        /* Search for objects using filter and controls */
        NamingEnumeration<SearchResult> answer = ctx.search(personDN, filter, ctls);

        /* close the connection */
        ctx.close();

        if (answer == null || !answer.hasMore()) {
            return -1;
        }

        SearchResult sr = answer.next();
        Attributes attrs = sr.getAttributes();
        String cn = attrs.get("cn").toString();
        if (log.isDebugEnabled()) {
            log.debug("cn of user with eMail (" + emailAddr + ") is " + cn);
        }

        /*
         * cn could be in the format "cn: Peter Smith, Pete Smith, Smithy" so we need to capture
         * just the first entry
         */
        if (cn != null) {
            if (cn.contains(",")) {
                cn = cn.split(",")[0];
                if (cn.contains(":")) {
                    cn = cn.split(":")[1];
                }
            } else if (cn.contains(":")) {
                cn = cn.split(":")[1];
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Cleaned cn of user with eMail (" + emailAddr + ") is " + cn);
        }

        /* Now we try to bind as the user */
        String userName = "cn=" + cn + "," + personDN;

        if (log.isDebugEnabled()) {
            log.debug("LDAP user name of user with eMail (" + emailAddr + ") is " + userName);
        }

        /* Bind as the user */
        environment.put(Context.SECURITY_PRINCIPAL, userName);
        environment.put(Context.SECURITY_CREDENTIALS, password);
        try {
            ctx = new InitialDirContext(environment);
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("Could not bind user " + userName);
            }
            return -1;
        }
        ctx.close();
        if (log.isDebugEnabled()) {
            log.debug("user with eMail (" + emailAddr + ") was successfully authenticated using LDAP");
        }
        return 1;
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.error("Received an exception while closing the LDAP DirContext", e);
            }
        }
    }
}