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:com.alfaariss.oa.engine.attribute.gather.processor.jndi.JNDIGatherer.java

/**
 * Reads JNDI connection information from the configuration.
 * <br>//  w  w w.j  av a2  s. c  om
 * Creates an <code>Hashtable</code> containing the JNDI environment variables.
 * @param oConfigurationManager The configuration manager
 * @param eConfig the configuration section
 * @return <code>DirContext</code> that contains the JNDI connection
 * @throws AttributeException if configuration reading fails
 */
private Hashtable<String, String> readJNDIContext(IConfigurationManager oConfigurationManager, Element eConfig)
        throws AttributeException {
    Hashtable<String, String> htEnvironment = new Hashtable<String, String>(11);

    try {
        Element eSecurityPrincipal = oConfigurationManager.getSection(eConfig, "security_principal");
        if (eSecurityPrincipal == null) {
            _logger.error("No 'security_principal' section found in 'resource' configuration");
            throw new AttributeException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sPrincipal = oConfigurationManager.getParam(eSecurityPrincipal, "dn");
        if (sPrincipal == null) {
            _logger.error("No item 'dn' item found in configuration");
            throw new AttributeException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sPassword = oConfigurationManager.getParam(eSecurityPrincipal, "password");
        if (sPassword == null) {
            _logger.error("No 'password' item found in configuration ");
            throw new AttributeException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sDriver = oConfigurationManager.getParam(eConfig, "driver");
        if (sDriver == null) {
            _logger.error("No 'driver' item found in configuration");
            throw new AttributeException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sUrl = oConfigurationManager.getParam(eConfig, "url");
        if (sUrl == null) {
            _logger.error("No valid config item 'url' found in configuration");
            throw new AttributeException(SystemErrors.ERROR_CONFIG_READ);
        }

        if (sUrl.length() >= 5 && sUrl.substring(0, 5).equalsIgnoreCase("ldaps")) {
            // Request SSL transport
            htEnvironment.put(Context.SECURITY_PROTOCOL, "ssl");
            _logger.info("SSL enabled");
        } else {
            _logger.info("SSL disabled");
        }

        htEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, sDriver);
        htEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple");
        htEnvironment.put(Context.SECURITY_PRINCIPAL, sPrincipal);
        htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword);
        htEnvironment.put(Context.PROVIDER_URL, sUrl);
    } catch (AttributeException e) {
        throw e;
    } catch (Exception e) {
        _logger.error("Could not create a connection", e);
        throw new AttributeException(SystemErrors.ERROR_INTERNAL);
    }
    return htEnvironment;
}

From source file:org.apache.ambari.server.serveraction.kerberos.ADKerberosOperationHandler.java

/**
 * Helper method to create the LDAP context needed to interact with the Active Directory.
 *
 * @return the relevant LdapContext//from w  w  w  . ja v  a  2s. c o m
 * @throws KerberosKDCConnectionException       if a connection to the KDC cannot be made
 * @throws KerberosAdminAuthenticationException if the administrator credentials fail to authenticate
 * @throws KerberosRealmException               if the realm does not map to a KDC
 * @throws KerberosOperationException           if an unexpected error occurred
 */
protected LdapContext createLdapContext() throws KerberosOperationException {
    KerberosCredential administratorCredentials = getAdministratorCredentials();

    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_CONTEXT_FACTORY_CLASS);
    properties.put(Context.PROVIDER_URL, ldapUrl);
    properties.put(Context.SECURITY_PRINCIPAL, administratorCredentials.getPrincipal());
    properties.put(Context.SECURITY_CREDENTIALS, administratorCredentials.getPassword());
    properties.put(Context.SECURITY_AUTHENTICATION, "simple");
    properties.put(Context.REFERRAL, "follow");
    properties.put("java.naming.ldap.factory.socket", TrustingSSLSocketFactory.class.getName());

    try {
        return createInitialLdapContext(properties, null);
    } catch (CommunicationException e) {
        String message = String.format("Failed to communicate with the Active Directory at %s: %s", ldapUrl,
                e.getMessage());
        LOG.warn(message, e);
        throw new KerberosKDCConnectionException(message, e);
    } catch (AuthenticationException e) {
        String message = String.format("Failed to authenticate with the Active Directory at %s: %s", ldapUrl,
                e.getMessage());
        LOG.warn(message, e);
        throw new KerberosAdminAuthenticationException(message, e);
    } catch (NamingException e) {
        String error = e.getMessage();

        if ((error != null) && !error.isEmpty()) {
            String message = String.format("Failed to communicate with the Active Directory at %s: %s", ldapUrl,
                    e.getMessage());
            LOG.warn(message, e);

            if (error.startsWith("Cannot parse url:")) {
                throw new KerberosKDCConnectionException(message, e);
            } else {
                throw new KerberosOperationException(message, e);
            }
        } else {
            throw new KerberosOperationException("Unexpected error condition", e);
        }
    }
}

From source file:org.apache.syncope.fit.core.reference.AbstractITCase.java

@SuppressWarnings({ "unchecked", "rawtypes", "UseOfObsoleteCollectionType" })
protected InitialDirContext getLdapResourceDirContext(final String bindDn, final String bindPwd)
        throws NamingException {
    ResourceTO ldapRes = resourceService.read(RESOURCE_NAME_LDAP);
    final Map<String, ConnConfProperty> ldapConnConf = connectorService.read(ldapRes.getConnector())
            .getConfigurationMap();/*w  w w  .j av  a2 s .c  o m*/

    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://" + ldapConnConf.get("host").getValues().get(0) + ":"
            + ldapConnConf.get("port").getValues().get(0) + "/");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL,
            bindDn == null ? ldapConnConf.get("principal").getValues().get(0) : bindDn);
    env.put(Context.SECURITY_CREDENTIALS,
            bindPwd == null ? ldapConnConf.get("credentials").getValues().get(0) : bindPwd);

    return new InitialDirContext(env);
}

From source file:de.sub.goobi.helper.ldap.Ldap.java

/**
 * change password of given user, needs old password for authentication.
 *
 * @param inUser/*from w  w w  .  j  av a  2s.c om*/
 *            User object
 * @param inOldPassword
 *            String
 * @param inNewPassword
 *            String
 * @return boolean about result of change
 */
public boolean changeUserPassword(User inUser, String inOldPassword, String inNewPassword)
        throws NoSuchAlgorithmException {
    MD4 digester = new MD4();
    Hashtable<String, String> env = getLdapConnectionSettings();
    if (!ConfigCore.getBooleanParameter("ldap_readonly", false)) {
        env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
        env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));

        try {
            DirContext ctx = new InitialDirContext(env);

            /*
             * Encryption of password and Base64-Encoding
             */
            MessageDigest md = MessageDigest.getInstance(ConfigCore.getParameter("ldap_encryption", "SHA"));
            md.update(inNewPassword.getBytes(StandardCharsets.UTF_8));
            String digestBase64 = new String(Base64.encodeBase64(md.digest()), StandardCharsets.UTF_8);
            ModificationItem[] mods = new ModificationItem[4];

            /*
             * UserPasswort-Attribut ndern
             */
            BasicAttribute userpassword = new BasicAttribute("userPassword",
                    "{" + ConfigCore.getParameter("ldap_encryption", "SHA") + "}" + digestBase64);

            /*
             * LanMgr-Passwort-Attribut ndern
             */
            BasicAttribute lanmgrpassword = null;
            try {
                lanmgrpassword = new BasicAttribute("sambaLMPassword",
                        LdapUser.toHexString(LdapUser.lmHash(inNewPassword)));
                // TODO: Don't catch super class exception, make sure that
                // the password isn't logged here
            } catch (Exception e) {
                logger.error(e);
            }

            /*
             * NTLM-Passwort-Attribut ndern
             */
            BasicAttribute ntlmpassword = null;
            try {
                byte hmm[] = digester.digest(inNewPassword.getBytes("UnicodeLittleUnmarked"));
                ntlmpassword = new BasicAttribute("sambaNTPassword", LdapUser.toHexString(hmm));
            } catch (UnsupportedEncodingException e) {
                // TODO: Make sure that the password isn't logged here
                logger.error(e);
            }

            BasicAttribute sambaPwdLastSet = new BasicAttribute("sambaPwdLastSet",
                    String.valueOf(System.currentTimeMillis() / 1000l));

            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userpassword);
            mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, lanmgrpassword);
            mods[2] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, ntlmpassword);
            mods[3] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, sambaPwdLastSet);
            ctx.modifyAttributes(getUserDN(inUser), mods);

            // Close the context when we're done
            ctx.close();
            return true;
        } catch (NamingException e) {
            logger.debug("Benutzeranmeldung nicht korrekt oder Passwortnderung nicht mglich", e);
            return false;
        }
    }
    return false;
}

From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java

/**
 * Reads JNDI connection information from the configuration.
 * <br>//  w  w  w  . j  av a2s .  c  o  m
 * Creates an <code>Hashtable</code> containing the JNDI environment variables.
 * @param oConfigurationManager The configuration manager
 * @param eConfig the configuration section
 * @return <code>DirContext</code> that contains the JNDI connection
 * @throws UserException if configuration reading fails
 */
private Hashtable<String, String> readJNDIContext(IConfigurationManager oConfigurationManager, Element eConfig)
        throws UserException {
    Hashtable<String, String> htEnvironment = new Hashtable<String, String>();

    try {
        Element eSecurityPrincipal = oConfigurationManager.getSection(eConfig, "security_principal");
        if (eSecurityPrincipal == null) {
            _logger.error("No 'security_principal' section found in 'resource' configuration");
            throw new UserException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sPrincipal = oConfigurationManager.getParam(eSecurityPrincipal, "dn");
        if (sPrincipal == null) {
            _logger.error("No item 'dn' item found in configuration");
            throw new UserException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sPassword = oConfigurationManager.getParam(eSecurityPrincipal, "password");
        if (sPassword == null) {
            _logger.error("No 'password' item found in configuration ");
            throw new UserException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sDriver = oConfigurationManager.getParam(eConfig, "driver");
        if (sDriver == null) {
            _logger.error("No 'driver' item found in configuration");
            throw new UserException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sUrl = oConfigurationManager.getParam(eConfig, "url");
        if (sUrl == null) {
            _logger.error("No valid config item 'url' found in configuration");
            throw new UserException(SystemErrors.ERROR_CONFIG_READ);
        }

        if (sUrl.length() >= 5 && sUrl.substring(0, 5).equalsIgnoreCase("ldaps")) {
            // Request SSL transport
            htEnvironment.put(Context.SECURITY_PROTOCOL, "ssl");
            _logger.info("SSL enabled");
        } else {
            _logger.info("SSL disabled");
        }

        htEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, sDriver);
        htEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple");
        htEnvironment.put(Context.SECURITY_PRINCIPAL, sPrincipal);
        htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword);
        htEnvironment.put(Context.PROVIDER_URL, sUrl);

    } catch (UserException e) {
        throw e;
    } catch (Exception e) {
        _logger.error("Could not create a connection", e);
        throw new UserException(SystemErrors.ERROR_INTERNAL, e);
    }
    return htEnvironment;
}

From source file:org.apache.james.user.ldap.ReadOnlyUsersLDAPRepository.java

protected Properties getContextEnvironment() {
    final Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
    props.put(Context.PROVIDER_URL, null == ldapHost ? "" : ldapHost);
    if (null == credentials || credentials.isEmpty()) {
        props.put(Context.SECURITY_AUTHENTICATION, LdapConstants.SECURITY_AUTHENTICATION_NONE);
    } else {//w ww.  j a  v a2  s .  c o m
        props.put(Context.SECURITY_AUTHENTICATION, LdapConstants.SECURITY_AUTHENTICATION_SIMPLE);
        props.put(Context.SECURITY_PRINCIPAL, null == principal ? "" : principal);
        props.put(Context.SECURITY_CREDENTIALS, credentials);
    }
    // The following properties are specific to com.sun.jndi.ldap.LdapCtxFactory
    props.put(PROPERTY_NAME_CONNECTION_POOL, Boolean.toString(useConnectionPool));
    if (connectionTimeout > -1) {
        props.put(PROPERTY_NAME_CONNECT_TIMEOUT, Integer.toString(connectionTimeout));
    }
    if (readTimeout > -1) {
        props.put(PROPERTY_NAME_READ_TIMEOUT, Integer.toString(readTimeout));
    }
    return props;
}

From source file:org.hyperic.hq.product.jmx.MxUtil.java

public static JMXConnector getMBeanConnector(Properties config) throws MalformedURLException, IOException {

    String jmxUrl = config.getProperty(MxUtil.PROP_JMX_URL);
    Map map = new HashMap();

    String user = config.getProperty(PROP_JMX_USERNAME);
    String pass = config.getProperty(PROP_JMX_PASSWORD);

    map.put(JMXConnector.CREDENTIALS, new String[] { user, pass });

    // required for Oracle AS
    String providerPackages = config.getProperty(PROP_JMX_PROVIDER_PKGS);
    if (providerPackages != null)
        map.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, providerPackages);

    if (jmxUrl == null) {
        throw new MalformedURLException(PROP_JMX_URL + "==null");
    }/*from  w ww  .  jav  a2  s .c  o  m*/

    if (jmxUrl.startsWith(PTQL_PREFIX)) {
        jmxUrl = getUrlFromPid(jmxUrl.substring(PTQL_PREFIX.length()));
    }

    JMXServiceURL url = new JMXServiceURL(jmxUrl);

    String proto = url.getProtocol();
    if (proto.equals("t3") || proto.equals("t3s")) {
        //http://edocs.bea.com/wls/docs92/jmx/accessWLS.html
        //WebLogic support, requires:
        //cp $WLS_HOME/server/lib/wljmxclient.jar pdk/lib/
        //cp $WLS_HOME/server/lib/wlclient.jar pdk/lib/
        map.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote");
        map.put(Context.SECURITY_PRINCIPAL, user);
        map.put(Context.SECURITY_CREDENTIALS, pass);
    }

    JMXConnector connector = JMXConnectorFactory.connect(url, map);
    if (log.isDebugEnabled()) {
        log.debug("created new JMXConnector url=" + url + ", classloader="
                + Thread.currentThread().getContextClassLoader());
    }
    return connector;
}

From source file:org.springframework.security.ldap.userdetails.LdapUserDetailsManager.java

private void changePasswordUsingAttributeModification(DistinguishedName userDn, String oldPassword,
        String newPassword) {//  w  w  w . j  av a2s . co m

    final ModificationItem[] passwordChange = new ModificationItem[] { new ModificationItem(
            DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(passwordAttributeName, newPassword)) };

    if (oldPassword == null) {
        template.modifyAttributes(userDn, passwordChange);
        return;
    }

    template.executeReadWrite(dirCtx -> {
        LdapContext ctx = (LdapContext) dirCtx;
        ctx.removeFromEnvironment("com.sun.jndi.ldap.connect.pool");
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, LdapUtils.getFullDn(userDn, ctx).toString());
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, oldPassword);
        // TODO: reconnect doesn't appear to actually change the credentials
        try {
            ctx.reconnect(null);
        } catch (javax.naming.AuthenticationException e) {
            throw new BadCredentialsException("Authentication for password change failed.");
        }

        ctx.modifyAttributes(userDn, passwordChange);

        return null;
    });

}

From source file:org.wso2.carbon.connector.integration.test.ldap.LdapConnectorIntegrationTest.java

public void createSampleEntity() throws Exception {

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    env.put(Context.PROVIDER_URL, providerUrl);
    env.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, securityCredentials);

    DirContext ctx = new InitialDirContext(env);
    Attributes entry = new BasicAttributes();
    Attribute obClassAttr = new BasicAttribute("objectClass");
    obClassAttr.add("inetOrgPerson");
    entry.put(obClassAttr);// ww  w .j  a va 2s.  co  m

    Attribute mailAttr = new BasicAttribute("mail");
    mailAttr.add(testUserId + "@wso2.com");
    entry.put(mailAttr);

    Attribute passAttr = new BasicAttribute("userPassword");
    passAttr.add("12345");
    entry.put(passAttr);

    Attribute snAttr = new BasicAttribute("sn");
    snAttr.add("dim");
    entry.put(snAttr);

    Attribute cnAttr = new BasicAttribute("cn");
    cnAttr.add("dim");
    entry.put(cnAttr);

    String dn = "uid=" + testUserId + "," + userBase;

    ctx.createSubcontext(dn, entry);
}

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

private boolean isPasswordCorrectForAuthWithTLS(Hashtable<String, String> env, User user, String password) {
    env.put("java.naming.ldap.version", "3");
    LdapContext ctx = null;/*from   ww  w  .  j  av a 2  s  .c  o  m*/
    StartTlsResponse tls = null;
    try {
        ctx = new InitialLdapContext(env, null);

        // Authentication must be performed over a secure channel
        tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
        tls.negotiate();

        // Authenticate via SASL EXTERNAL mechanism using client X.509
        // certificate contained in JVM keystore
        ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, buildUserDN(user));
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
        ctx.reconnect(null);
        return true;
        // perform search for privileged attributes under authenticated context
    } catch (IOException e) {
        logger.error("TLS negotiation error:", e);
        return false;
    } catch (NamingException e) {
        logger.error("JNDI error:", e);
        return false;
    } finally {
        closeConnections(ctx, tls);
    }
}