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.jasig.cas.adaptors.ldap.util.AuthenticatedLdapContextSource.java

public DirContext getDirContext(final String principal, final String credentials) {
    final Hashtable<String, String> environment = (Hashtable) getAnonymousEnv().clone();

    environment.put(Context.SECURITY_PRINCIPAL, principal);
    environment.put(Context.SECURITY_CREDENTIALS, credentials);

    environment.remove("com.sun.jndi.ldap.connect.pool"); // remove this since we're modifying principal

    try {/* w  w w  . j  ava 2 s .c o m*/
        return getDirContextInstance(environment);
    } catch (final NamingException e) {
        throw new DataAccessResourceFailureException("Unable to create DirContext");
    }
}

From source file:cyrille.jndi.LdapTest.java

@Test
public void test() 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://localhost:389");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    DirContext dirContext = new InitialDirContext(env);

    Attributes attributes = dirContext.getAttributes("uid=aeinstein,ou=Users,dc=example,dc=com");
    for (NamingEnumeration<Attribute> attributesEnumeration = (NamingEnumeration<Attribute>) attributes
            .getAll(); attributesEnumeration.hasMore();) {
        Attribute attribute = attributesEnumeration.next();
        System.out.print(attribute.getID() + "=");

        for (NamingEnumeration<?> attributeValues = attribute.getAll(); attributeValues.hasMore();) {
            Object value = attributeValues.next();
            if (value instanceof byte[] && "userpassword".equals(attribute.getID())) {
                byte[] bytes = (byte[]) value;
                System.out.print(new String(bytes) + ", ");
            } else {
                System.out.print(value + ", ");
            }//from  w  w  w.  j a  va  2 s .c  o m
        }
        System.out.println();
    }
}

From source file:io.lavagna.service.LdapConnection.java

InitialDirContextCloseable context(String providerUrl, String principal, String password)
        throws NamingException {
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, providerUrl);
    env.put(Context.SECURITY_PRINCIPAL, principal);
    env.put(Context.SECURITY_CREDENTIALS, password);
    return new InitialDirContextCloseable(env);
}

From source file:pl.umk.mat.zawodyweb.ldap.LdapConnector.java

/**
 * Check user password and return that user
 *
 * Example of LDAP data://from  w  w w.j ava 2 s .c o  m
 * <pre>
 * dn: uid=faramir,ou=People,ou=int,dc=mat,dc=uni,dc=torun,dc=pl
 * objectClass: top
 * objectClass: account
 * objectClass: posixAccount
 * objectClass: shadowAccount
 * objectClass: radiusprofile
 * objectClass: sambaSamAccount
 * dialupAccess: yes
 * uid: faramir
 * cn: Marek Nowicki
 * loginShell: /bin/tcsh
 * uidNumber: 30030
 * sambaSID: S-1-30030
 * gecos: Marek Nowicki, doktorant Info.
 * gidNumber: 160
 * homeDirectory: /studdok/faramir
 * radiusSimultaneousUse: 1</pre>
 * @param login login
 * @param pass user password
 * @return Users if user found and password is OK or null if anything failed
 */
public static Users retieveUser(String login, String pass) {
    if (pass == null || pass.isEmpty() || login == null || login.isEmpty() || login.contains(",")) {
        return null;
    }

    Hashtable<String, String> ldapEnv = new Hashtable<String, String>(11);
    String dn = String.format("uid=%s,%s", login, baseDN);

    ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    ldapEnv.put(Context.PROVIDER_URL, ldapURL);
    ldapEnv.put(Context.SECURITY_PRINCIPAL, dn);
    ldapEnv.put(Context.SECURITY_CREDENTIALS, pass);

    try {
        DirContext authContext = new InitialDirContext(ldapEnv);
        Attributes userAttributes = authContext.getAttributes(dn);

        if (userAttributes.get("uidNumber") == null) {
            return null;
        }

        Attribute cn = userAttributes.get("cn"); // commonName - eg. Marek Nowicki

        String name = ((String) cn.get());
        String firstName = name;
        String lastName = "(LDAP)";

        int index = name.lastIndexOf(" ");
        if (index > 0) {
            firstName = name.substring(0, index).trim();
            lastName = name.substring(index + 1).trim();
        }

        Users user = new Users();

        user.setLogin(login);
        user.setFirstname(firstName);
        user.setLastname(lastName);
        user.setEmail(login + emailSuffix);

        return user;
    } catch (AuthenticationException ex) {
    } catch (NamingException ex) {
    } catch (NullPointerException ex) {
    } catch (ClassCastException ex) {
    } catch (Exception ex) {
        log.fatal("LDAP Exception:", ex);
    }
    return null;
}

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

private static DirContext getContext() 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_PRINCIPAL, rb.getString("rootDN"));
    env.put(Context.SECURITY_AUTHENTICATION, "none");
    return new InitialDirContext(env);
}

From source file:org.wso2.carbon.connector.ldap.LDAPUtils.java

protected static DirContext getDirectoryContext(MessageContext messageContext) throws NamingException {
    String providerUrl = LDAPUtils.lookupContextParams(messageContext, LDAPConstants.PROVIDER_URL);
    String securityPrincipal = LDAPUtils.lookupContextParams(messageContext, LDAPConstants.SECURITY_PRINCIPAL);
    String securityCredentials = LDAPUtils.lookupContextParams(messageContext,
            LDAPConstants.SECURITY_CREDENTIALS);
    boolean secureConnection = Boolean
            .valueOf(LDAPUtils.lookupContextParams(messageContext, LDAPConstants.SECURE_CONNECTION));
    boolean disableSSLCertificateChecking = Boolean
            .valueOf(LDAPUtils.lookupContextParams(messageContext, LDAPConstants.DISABLE_SSL_CERT_CHECKING));

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, LDAPConstants.COM_SUN_JNDI_LDAP_LDAPCTXFACTORY);
    env.put(Context.PROVIDER_URL, providerUrl);
    env.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, securityCredentials);
    if (secureConnection) {
        env.put(Context.SECURITY_PROTOCOL, LDAPConstants.SSL);
    }/*  w  ww  .  j  a  v a 2 s. c  o  m*/
    if (disableSSLCertificateChecking) {
        env.put(LDAPConstants.JAVA_NAMING_LDAP_FACTORY_SOCKET,
                LDAPConstants.ORG_WSO2_CARBON_CONNECTOR_SECURITY_MYSSLSOCKETFACTORY);
    }

    DirContext ctx = null;
    ctx = new InitialDirContext(env);
    return ctx;
}

From source file:com.jaspersoft.jasperserver.api.security.externalAuth.ldap.JSLdapContextSource.java

public DirContext getReadWriteContext(String userDn, Object credentials) {
    Hashtable env = new Hashtable(getAnonymousEnv());

    env.put(Context.SECURITY_PRINCIPAL, userDn);
    env.put(Context.SECURITY_CREDENTIALS, credentials);
    env.remove(SUN_LDAP_POOLING_FLAG);/*from  ww w . ja v a  2  s  .  c o m*/

    if (logger.isDebugEnabled()) {
        logger.debug("Creating context with principal: '" + userDn + "'");
    }

    return createContext(env);
}

From source file:org.jasig.cas.adaptors.ldap.DigestMd5DirContextAuthenticationStrategy.java

/** {@inheritDoc} */
@SuppressWarnings(value = "unchecked")
public void setupEnvironment(final Hashtable env, final String userDn, final String password)
        throws NamingException {

    env.put(Context.SECURITY_AUTHENTICATION, DIGEST_MD5_AUTHENTICATION);
    // userDn should be a bare username for DIGEST-MD5
    env.put(Context.SECURITY_PRINCIPAL, userDn);
    env.put(Context.SECURITY_CREDENTIALS, password);

}

From source file:org.eclipselabs.etrack.util.security.ldap.impl.LdapSecurityService.java

@Override
public boolean authenticate(String id, char[] password) {
    String cachedPassword = credentialCache.get(id);
    String encodedPassword = null;

    try {//from ww w . j  a v a2  s.  c  o  m
        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:org.apache.jmeter.protocol.jms.client.InitialContextFactory.java

/**
 * Look up the context from the local cache, creating it if necessary.
 * //from  w w w.ja va2s.  c  o m
 * @param initialContextFactory used to set the property {@link Context#INITIAL_CONTEXT_FACTORY}
 * @param providerUrl used to set the property {@link Context#PROVIDER_URL}
 * @param useAuth set <code>true</code> if security is to be used.
 * @param securityPrincipal used to set the property {@link Context#SECURITY_PRINCIPAL}
 * @param securityCredentials used to set the property {@link Context#SECURITY_CREDENTIALS}
 * @return the context, never <code>null</code>
 * @throws NamingException when creation of the context fails
 */
public static Context lookupContext(String initialContextFactory, String providerUrl, boolean useAuth,
        String securityPrincipal, String securityCredentials) throws NamingException {
    String cacheKey = createKey(Thread.currentThread().getId(), initialContextFactory, providerUrl,
            securityPrincipal, securityCredentials);
    Context ctx = MAP.get(cacheKey);
    if (ctx == null) {
        Properties props = new Properties();
        props.setProperty(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
        props.setProperty(Context.PROVIDER_URL, providerUrl);
        if (useAuth && securityPrincipal != null && securityCredentials != null
                && securityPrincipal.length() > 0 && securityCredentials.length() > 0) {
            props.setProperty(Context.SECURITY_PRINCIPAL, securityPrincipal);
            props.setProperty(Context.SECURITY_CREDENTIALS, securityCredentials);
            log.info("authentication properties set");
        }
        try {
            ctx = new InitialContext(props);
        } catch (NoClassDefFoundError | Exception e) {
            throw new NamingException(e.toString());
        }
        // we want to return the context that is actually in the map
        // if it's the first put we will have a null result
        Context oldCtx = MAP.putIfAbsent(cacheKey, ctx);
        if (oldCtx != null) {
            // There was an object in map, destroy the temporary and return one in map (oldCtx)
            try {
                ctx.close();
            } catch (Exception e) {
                // NOOP
            }
            ctx = oldCtx;
        }
        // else No object in Map, ctx is the one
    }
    return ctx;
}