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.eclipselabs.etrack.util.security.ldap.impl.LdapService.java

@Override
public boolean authenticate(String id, char[] password) {
    if (id == null || id.isEmpty())
        return false;

    if (idSuffix != null)
        id = id + idSuffix;/*from w w  w .  j  a  v  a2s . co  m*/

    String cachedPassword = credentialCache.get(id);
    String encodedPassword = null;

    try {
        encodedPassword = codec.encode(new String(password));
    } catch (EncoderException e1) {
    }

    if (cachedPassword != null && encodedPassword != null && cachedPassword.equals(encodedPassword))
        return true;

    Hashtable<String, String> environment = new Hashtable<String, String>();
    environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environment.put(Context.PROVIDER_URL, url);
    environment.put(Context.SECURITY_AUTHENTICATION, "simple");
    environment.put(Context.SECURITY_PRINCIPAL, id);
    environment.put(Context.SECURITY_CREDENTIALS, new String(password));

    try {
        InitialDirContext context = new InitialDirContext(environment);
        context.close();

        if (encodedPassword != null)
            credentialCache.put(id, encodedPassword);

        return true;
    } catch (NamingException e) {
        return false;
    }
}

From source file:com.jaeksoft.searchlib.util.ActiveDirectory.java

public ActiveDirectory(String username, String password, String domain) throws NamingException {
    if (StringUtils.isEmpty(domain))
        throw new NamingException("The domain is empty");
    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    properties.put(Context.PROVIDER_URL, StringUtils.fastConcat("LDAP://", domain));
    properties.put(Context.SECURITY_PRINCIPAL, StringUtils.fastConcat(username, "@", domain));
    properties.put(Context.SECURITY_CREDENTIALS, password);
    properties.put("java.naming.ldap.attributes.binary", "objectSID");
    properties.put(Context.REFERRAL, "follow");
    dirContext = new InitialDirContext(properties);
    domainSearchName = getDomainSearch(domain);
}

From source file:org.malaguna.cmdit.service.ldap.LDAPBase.java

public Attributes loadUser(String uid, String[] attrs) {

    // Preparar las variables de entorno para la conexin JNDI
    Hashtable<String, String> entorno = new Hashtable<String, String>();

    // Credenciales del usuario para realizar la bsqueda
    String cadena = "uid=" + user + "," + context;

    entorno.put(Context.PROVIDER_URL, server);
    entorno.put(Context.INITIAL_CONTEXT_FACTORY, initContext);
    if (password != null && user != null) {
        entorno.put(Context.SECURITY_PRINCIPAL, cadena);
        entorno.put(Context.SECURITY_CREDENTIALS, password);
    }//w ww .jav a2  s . co m

    Attributes atributos = null;

    try {
        // Crear contexto de directorio inicial
        DirContext ctx = new InitialDirContext(entorno);

        // Recuperar atributos del usuario que se est buscando
        if (attrs != null)
            atributos = ctx.getAttributes("uid=" + uid + "," + context, attrs);
        else
            atributos = ctx.getAttributes("uid=" + uid + "," + context);

        // Cerrar la conexion
        ctx.close();
    } catch (NamingException e) {
        logger.error(messages.getMessage("err.ldap.attribute", new Object[] { e }, Locale.getDefault()));
    }

    return atributos;

}

From source file:org.apache.directory.server.core.jndi.LdapJndiPropertiesTest.java

License:asdf

@Test
public void testNoAuthWithCredsEnv() throws Exception {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "asdf");
    env.put(Context.PROVIDER_URL, "");
    LdapJndiProperties props = LdapJndiProperties.getLdapJndiProperties(env);
    assertEquals(AuthenticationLevel.SIMPLE, props.getAuthenticationLevel());
    assertTrue(ArrayUtils.isEquals(Strings.getBytesUtf8("asdf"), props.getCredentials()));
}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

private static DirContext getAuthContext(String userCN, String password, boolean dedicatedAdminUser)
        throws NamingException {
    ResourceBundle rb = ResourceBundle.getBundle("ldap");
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, rb.getString("url"));
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    if (dedicatedAdminUser) {
        env.put(Context.SECURITY_PRINCIPAL, rb.getString("bindDN"));
        env.put(Context.SECURITY_CREDENTIALS, rb.getString("bindPass"));
    } else {/*w ww .  j  a va 2  s .com*/
        env.put(Context.SECURITY_PRINCIPAL, "cn=" + userCN + "," + rb.getString("peopleRoot"));
        env.put(Context.SECURITY_CREDENTIALS, password);
    }

    return new InitialDirContext(env);

}

From source file:de.tuttas.util.LDAPUtil.java

/**
 * Benutzer aus der LDAP Abfragen//from   w  w w.  j  av a 2 s . com
 *
 * @param username Benutzername
 * @param password Kennwort
 * @return der Benutzer
 * @throws Exception Wenn etwas schief ging
 */
public LDAPUser authenticateJndi(String username, String password) throws Exception {
    // Anbindung ans LDAP
    Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.PROVIDER_URL, Config.getInstance().ldaphost);
    props.put(Context.SECURITY_PRINCIPAL, Config.getInstance().bindUser);//adminuser - User with special priviledge, dn user
    props.put(Context.SECURITY_CREDENTIALS, Config.getInstance().bindPassword);//dn user password
    try {
        context = new InitialDirContext(props);
        ctrls = new SearchControls();
        ctrls.setReturningAttributes(new String[] { "description", "mail", "sn", "initials", "givenName",
                "memberOf", "userPrincipalName", "distinguishedName" });
        ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    } catch (NamingException ex) {
        Logger.getLogger(LDAPUtil.class.getName()).log(Level.SEVERE, null, ex);
    }
    NamingEnumeration<javax.naming.directory.SearchResult> answers = context
            .search(Config.getInstance().userContext, "(cn=" + username + ")", ctrls);
    Log.d("answers=" + answers);
    Log.d("answers=" + answers.hasMore());

    if (!answers.hasMore()) {
        return null;
    }

    javax.naming.directory.SearchResult result = answers.nextElement();

    try {
        for (NamingEnumeration ae = result.getAttributes().getAll(); ae.hasMore();) {
            Attribute attr = (Attribute) ae.next();
            Log.d("attribute: " + attr.getID());

            /* print each value */
            for (NamingEnumeration e = attr.getAll(); e.hasMore(); System.out.println("value: " + e.next()))
                ;
        }
    } catch (NamingException e) {
        e.printStackTrace();
    }

    String inititials = "";
    if (result.getAttributes().get("initials") != null) {
        inititials = result.getAttributes().get("initials").getAll().next().toString();
    }
    LDAPUser u;
    if (result.getAttributes().get("mail") == null) {
        u = new LDAPUser(result.getAttributes().get("sn").getAll().next().toString(),
                result.getAttributes().get("givenName").getAll().next().toString(), "", inititials);
    } else {
        u = new LDAPUser(result.getAttributes().get("sn").getAll().next().toString(),
                result.getAttributes().get("givenName").getAll().next().toString(),
                result.getAttributes().get("mail").getAll().next().toString(), inititials);
    }

    String dName = result.getAttributes().get("distinguishedName").getAll().next().toString();
    Log.d("dName=" + dName);
    if (dName.contains("OU=Lehrer")) {
        Log.d("Ich bin ein Lehrer");
        u.setRole(Roles.toString(Roles.LEHRER));
    } else {
        Log.d("Ich bin ein Schler");
        u.setRole(Roles.toString(Roles.SCHUELER));
        if (result.getAttributes().get("memberOf") != null) {
            String memberOf = result.getAttributes().get("memberOf").getAll().next().toString();
            String courseName = memberOf.split(",")[0];
            courseName = courseName.substring(courseName.indexOf("=") + 1);
            Log.d("Name der Klasse ist " + courseName);
            u.setCourse(courseName);
        }
    }

    String user = result.getNameInNamespace();

    try {

        props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, Config.getInstance().ldaphost);
        props.put(Context.SECURITY_PRINCIPAL, user);
        props.put(Context.SECURITY_CREDENTIALS, password);

        context = new InitialDirContext(props);
    } catch (Exception e) {
        return null;
    }
    return u;
}

From source file:io.apiman.gateway.engine.policies.auth.LDAPIdentityValidator.java

/**
 * @see io.apiman.gateway.engine.policies.auth.IIdentityValidator#validate(java.lang.String, java.lang.String, io.apiman.gateway.engine.beans.ServiceRequest, io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object, io.apiman.gateway.engine.async.IAsyncHandler)
 *///ww w .  j  ava 2s.  co  m
@Override
public void validate(String username, String password, ServiceRequest request, IPolicyContext context,
        LDAPIdentitySource config, IAsyncResultHandler<Boolean> handler) {
    String url = config.getUrl();
    String dn = formatDn(config.getDnPattern(), username, request);

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); //$NON-NLS-1$
    env.put(Context.PROVIDER_URL, url);

    env.put(Context.SECURITY_AUTHENTICATION, "simple"); //$NON-NLS-1$
    env.put(Context.SECURITY_PRINCIPAL, dn);
    env.put(Context.SECURITY_CREDENTIALS, password);
    try {
        new InitialDirContext(env);
        handler.handle(AsyncResultImpl.create(Boolean.TRUE));
    } catch (AuthenticationException e) {
        handler.handle(AsyncResultImpl.create(Boolean.FALSE));
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.wso2.carbon.registry.caching.invalidator.connection.JMSNotification.java

@Override
public void createConnection(Properties config) {
    try {/*from w  ww  .  ja va 2 s  .  c  om*/
        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, config.getProperty("initialContextFactory"));
        props.put(Context.PROVIDER_URL, config.getProperty("providerUrl"));
        props.put(Context.SECURITY_PRINCIPAL, config.getProperty("securityPrincipal"));
        props.put(Context.SECURITY_CREDENTIALS, config.getProperty("securityCredentials"));
        props.put("topic.cacheInvalidateTopic", config.getProperty("cacheInvalidateTopic"));
        InitialContext jndi = new InitialContext(props);
        ConnectionFactory connectionFactory = (ConnectionFactory) jndi.lookup("ConnectionFactory");
        destination = (Destination) jndi.lookup("cacheInvalidateTopic");

        connection = connectionFactory.createConnection(config.getProperty("securityPrincipal"),
                config.getProperty("securityCredentials"));
        connection.start();
    } catch (NamingException | JMSException e) {
        log.error("Global cache invalidation: Error message broker initialization", e);
    }
}

From source file:br.com.upic.camel.ldap.LdapEndpoint.java

@Override
protected void onExchange(final Exchange exchange) throws Exception {
    LOG.info("Setting up the context");

    final Hashtable<String, String> conf = new Hashtable<String, String>();

    LOG.debug("Initial Context Factory = " + initialContextFactory);

    conf.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);

    LOG.debug("Provider URL = " + providerUrl);

    conf.put(Context.PROVIDER_URL, providerUrl);

    LOG.debug("Security Authentication = " + securityAuthentication);

    conf.put(Context.SECURITY_AUTHENTICATION, securityAuthentication);

    final Message in = exchange.getIn();

    final String user = in.getHeader(HEADER_USER, String.class);

    LOG.debug("User = " + user);

    conf.put(Context.SECURITY_PRINCIPAL, user);

    final String password = in.getHeader(HEADER_PASSWORD, String.class);

    LOG.debug("Password = " + password);

    conf.put(Context.SECURITY_CREDENTIALS, password);

    LOG.info("Authenticating in directory");

    final Message out = exchange.getOut();

    try {/*from   w w w.j a  va 2s .  c  o m*/
        new InitialContext(conf);

        out.setBody(true);
    } catch (final AuthenticationException e) {
        LOG.error(e.getMessage(), e);

        out.setBody(false);
    }

}

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

@SuppressWarnings({ "rawtypes", "unchecked" })
LDAPConnectionContext(Map<String, String> userStoreProperties) throws UserStoreException {

    String connectionURL = userStoreProperties.get(LDAPConstants.CONNECTION_URL);
    String connectionName = userStoreProperties.get(LDAPConstants.CONNECTION_NAME);
    String connectionPassword = userStoreProperties.get(LDAPConstants.CONNECTION_PASSWORD);

    if (log.isDebugEnabled()) {
        log.debug("Connection Name :: " + connectionName + ", Connection URL :: " + connectionURL);
    }//from  w  w w .  j a v a2s  . com

    environment = new Hashtable<>();
    environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environment.put(Context.SECURITY_AUTHENTICATION, "simple");

    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 = userStoreProperties.get(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 (userStoreProperties.get(LDAPConstants.PROPERTY_REFERRAL) != null) {
        environment.put("java.naming.referral", userStoreProperties.get(LDAPConstants.PROPERTY_REFERRAL));
    }
    //Set connect timeout if provided in configuration. Otherwise set default value
    String connectTimeout = userStoreProperties.get(CONNECTION_TIME_OUT);
    String readTimeout = userStoreProperties.get(READ_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");
    }

    if (StringUtils.isNotEmpty(readTimeout)) {
        environment.put("com.sun.jndi.ldap.read.timeout", readTimeout);
    }
}