Example usage for javax.naming.directory DirContext addToEnvironment

List of usage examples for javax.naming.directory DirContext addToEnvironment

Introduction

In this page you can find the example usage for javax.naming.directory DirContext addToEnvironment.

Prototype

public Object addToEnvironment(String propName, Object propVal) throws NamingException;

Source Link

Document

Adds a new environment property to the environment of this context.

Usage

From source file:NewConn.java

public static void main(String[] args) {
    // Set up environment for creating initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    try {//from w  ww.java  2  s  .  c  om
        // Create initial context (first connection)
        DirContext ctx = new InitialDirContext(env);

        // Get a copy of the same context
        DirContext ctx2 = (DirContext) ctx.lookup("");

        // Change authentication properties in ctx2
        ctx2.addToEnvironment(Context.SECURITY_PRINCIPAL, "cn=C. User, ou=NewHires, o=JNDITutorial");
        ctx2.addToEnvironment(Context.SECURITY_CREDENTIALS, "mysecret");

        // Method on ctx2 will use new connection
        System.out.println(ctx2.getAttributes("ou=NewHires"));

        // Close the contexts when we're done
        ctx.close();
        ctx2.close();
    } catch (NamingException e) {
        e.printStackTrace();
    }
}

From source file:UseDiff.java

public static void main(String[] args) {

    // Set up environment for creating initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    // Authenticate as S. User and password "mysecret"
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial");
    env.put(Context.SECURITY_CREDENTIALS, "mysecret");

    try {/*ww w  .  java2s . c  om*/
        // Create initial context
        DirContext ctx = new InitialDirContext(env);

        // do something useful with ctx
        System.out.println(ctx.lookup("ou=NewHires"));

        // Change to using no authentication
        ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "none");

        System.out.println(ctx.lookup("ou=NewHires"));

        // do something useful with ctx

        // Close the context when we're done
        ctx.close();
    } catch (NamingException e) {
        e.printStackTrace();
    }
}

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

/**
 * Binds the user to the context./*from   ww  w.j  a  va  2 s  . c o  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.hs.mail.security.login.JndiLoginModule.java

private boolean bindUser(DirContext context, String dn, String password) throws NamingException {
    boolean isValid = false;
    context.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
    context.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
    try {// w w w .ja v a  2  s .  c o  m
        context.getAttributes("", null);
        isValid = true;
    } catch (AuthenticationException e) {
    }
    if (StringUtils.isNotEmpty(this.username)) {
        context.addToEnvironment(Context.SECURITY_PRINCIPAL, this.username);
    } else {
        context.removeFromEnvironment(Context.SECURITY_PRINCIPAL);
    }
    if (StringUtils.isNotEmpty(this.password)) {
        context.addToEnvironment(Context.SECURITY_CREDENTIALS, this.password);
    } else {
        context.removeFromEnvironment(Context.SECURITY_CREDENTIALS);
    }
    return isValid;
}

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

private void setConnectionOptions(DirContext dirContext) throws UserManagerException {
    String errorMsgKey = UserManagerException.MSG_SET_CONNECTION_OPTIONS_ERROR;

    try {//from ww w. ja v  a  2  s . c  o m
        // unlimited size limit
        // wait for all results
        dirContext.addToEnvironment(DirContext.BATCHSIZE, "0");

    } catch (NamingException ex) {
        CATEGORY.error("UserManagerException is thrown from: " + "UserManagerLocal::setConnectionOptions(): ",
                ex);
        throw new UserManagerException(errorMsgKey, null, ex);
    }
}

From source file:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java

protected void bindUser(DirContext context, String dn) throws NamingException, FailedLoginException {

    context.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
    try {/*from   ww  w . ja  v a  2s.com*/
        context.getAttributes("", null);
    } catch (AuthenticationException e) {
        log.debug("Authentication failed for dn=" + dn);
        throw new FailedLoginException();
    } finally {

        if (connectionUsername != null) {
            context.addToEnvironment(Context.SECURITY_PRINCIPAL, connectionUsername);
        } else {
            context.removeFromEnvironment(Context.SECURITY_PRINCIPAL);
        }

        if (connectionPassword != null) {
            context.addToEnvironment(Context.SECURITY_CREDENTIALS, connectionPassword);
        } else {
            context.removeFromEnvironment(Context.SECURITY_CREDENTIALS);
        }
    }
}

From source file:org.jasig.portal.security.provider.SimpleLdapSecurityContext.java

/**
 * Authenticates the user.//from   w ww  .ja  va  2s  .c om
 */
public synchronized void authenticate() throws PortalSecurityException {
    this.isauth = false;
    ILdapServer ldapConn;

    String propFile = ctxProperties.getProperty(LDAP_PROPERTIES_CONNECTION_NAME);
    if (propFile != null && propFile.length() > 0)
        ldapConn = LdapServices.getLdapServer(propFile);
    else
        ldapConn = LdapServices.getDefaultLdapServer();

    String creds = new String(this.myOpaqueCredentials.credentialstring);
    if (this.myPrincipal.UID != null && !this.myPrincipal.UID.trim().equals("")
            && this.myOpaqueCredentials.credentialstring != null && !creds.trim().equals("")) {
        DirContext conn = null;
        NamingEnumeration results = null;
        StringBuffer user = new StringBuffer("(");
        String first_name = null;
        String last_name = null;

        user.append(ldapConn.getUidAttribute()).append("=");
        user.append(this.myPrincipal.UID).append(")");
        if (log.isDebugEnabled())
            log.debug("SimpleLdapSecurityContext: Looking for " + user.toString());

        try {
            conn = ldapConn.getConnection();

            // set up search controls
            SearchControls searchCtls = new SearchControls();
            searchCtls.setReturningAttributes(attributes);
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            // do lookup
            if (conn != null) {
                try {
                    results = conn.search(ldapConn.getBaseDN(), user.toString(), searchCtls);
                    if (results != null) {
                        if (!results.hasMore())
                            log.error("SimpleLdapSecurityContext: user not found , " + this.myPrincipal.UID);
                        while (results != null && results.hasMore()) {
                            SearchResult entry = (SearchResult) results.next();
                            StringBuffer dnBuffer = new StringBuffer();
                            dnBuffer.append(entry.getName()).append(", ");
                            dnBuffer.append(ldapConn.getBaseDN());
                            Attributes attrs = entry.getAttributes();
                            first_name = getAttributeValue(attrs, ATTR_FIRSTNAME);
                            last_name = getAttributeValue(attrs, ATTR_LASTNAME);
                            // re-bind as user
                            conn.removeFromEnvironment(javax.naming.Context.SECURITY_PRINCIPAL);
                            conn.removeFromEnvironment(javax.naming.Context.SECURITY_CREDENTIALS);
                            conn.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, dnBuffer.toString());
                            conn.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS,
                                    this.myOpaqueCredentials.credentialstring);
                            searchCtls = new SearchControls();
                            searchCtls.setReturningAttributes(new String[0]);
                            searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);

                            String attrSearch = "(" + ldapConn.getUidAttribute() + "=*)";
                            log.debug("SimpleLdapSecurityContext: Looking in " + dnBuffer.toString() + " for "
                                    + attrSearch);
                            conn.search(dnBuffer.toString(), attrSearch, searchCtls);

                            this.isauth = true;
                            this.myPrincipal.FullName = first_name + " " + last_name;
                            log.debug("SimpleLdapSecurityContext: User " + this.myPrincipal.UID + " ("
                                    + this.myPrincipal.FullName + ") is authenticated");

                            // Since LDAP is case-insensitive with respect to uid, force
                            // user name to lower case for use by the portal
                            this.myPrincipal.UID = this.myPrincipal.UID.toLowerCase();
                        } // while (results != null && results.hasMore())
                    } else {
                        log.error("SimpleLdapSecurityContext: No such user: " + this.myPrincipal.UID);
                    }
                } catch (AuthenticationException ae) {
                    log.info("SimpleLdapSecurityContext: Password invalid for user: " + this.myPrincipal.UID);
                } catch (Exception e) {
                    log.error("SimpleLdapSecurityContext: LDAP Error with user: " + this.myPrincipal.UID + "; ",
                            e);
                    throw new PortalSecurityException("SimpleLdapSecurityContext: LDAP Error" + e
                            + " with user: " + this.myPrincipal.UID);
                } finally {
                    ldapConn.releaseConnection(conn);
                }
            } else {
                log.error("LDAP Server Connection unavalable");
            }
        } catch (final NamingException ne) {
            log.error("Error geting connection to LDAP server.", ne);
        }
    } else {
        log.error("Principal or OpaqueCredentials not initialized prior to authenticate");
    }
    // Ok...we are now ready to authenticate all of our subcontexts.
    super.authenticate();
    return;
}