Example usage for javax.naming.ldap LdapContext getAttributes

List of usage examples for javax.naming.ldap LdapContext getAttributes

Introduction

In this page you can find the example usage for javax.naming.ldap LdapContext getAttributes.

Prototype

public Attributes getAttributes(Name name, String[] attrIds) throws NamingException;

Source Link

Document

Retrieves selected attributes associated with a named object.

Usage

From source file:edu.vt.middleware.ldap.AbstractLdap.java

/**
 * This will return the matching attributes associated with the supplied dn.
 * If retAttrs is null then all attributes will be returned. If retAttrs is an
 * empty array then no attributes will be returned. See {@link
 * javax.naming.DirContext#getAttributes(String, String[])}.
 *
 * @param  dn  <code>String</code> named object in the LDAP
 * @param  retAttrs  <code>String[]</code> attributes to return
 * @param  handler  <code>AttributeHandler[]</code> to post process results
 *
 * @return  <code>Attributes</code>
 *
 * @throws  NamingException  if the LDAP returns an error
 *//*from  w  w w.j  a  v a 2s.co m*/
protected Attributes getAttributes(final String dn, final String[] retAttrs, final AttributeHandler... handler)
        throws NamingException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Attribute search with the following parameters:");
        this.logger.debug("  dn = " + dn);
        this.logger.debug("  retAttrs = " + (retAttrs == null ? "all attributes" : Arrays.toString(retAttrs)));
        this.logger.debug("  handler = " + Arrays.toString(handler));
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("  config = " + this.config.getEnvironment());
        }
    }

    LdapContext ctx = null;
    Attributes attrs = null;
    try {
        for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) {
            try {
                ctx = this.getContext();
                attrs = ctx.getAttributes(dn, retAttrs);

                if (handler != null && handler.length > 0) {
                    final SearchCriteria sc = new SearchCriteria();
                    if (ctx != null && !"".equals(ctx.getNameInNamespace())) {
                        sc.setDn(ctx.getNameInNamespace());
                    } else {
                        sc.setDn(dn);
                    }
                    for (int j = 0; j < handler.length; j++) {
                        attrs = AttributesProcessor.executeHandler(sc, attrs, handler[j],
                                this.config.getHandlerIgnoreExceptions());
                    }
                }

                break;
            } catch (NamingException e) {
                this.operationRetry(ctx, e, i);
            }
        }
    } finally {
        if (ctx != null) {
            ctx.close();
        }
    }
    return attrs;
}

From source file:org.olat.ldap.LDAPLoginManagerImpl.java

/**
 * Connect to LDAP with the User-Name and Password given as parameters Configuration: LDAP URL = olatextconfig.xml (property=ldapURL) LDAP Base = olatextconfig.xml
 * (property=ldapBase) LDAP Attributes Map = olatextconfig.xml (property=userAttrs)
 * /* ww  w . j  ava 2  s  .  c o  m*/
 * @param uid The users LDAP login name (can't be null)
 * @param pwd The users LDAP password (can't be null)
 * @return After successful bind Attributes otherwise NULL
 * @throws NamingException
 */
public Attributes bindUser(final String uid, final String pwd, final LDAPError errors) {
    // get user name, password and attributes
    final String ldapUrl = LDAPLoginModule.getLdapUrl();
    final String[] userAttr = LDAPLoginModule.getUserAttrs();

    if (uid == null || pwd == null) {
        if (isLogDebugEnabled()) {
            logDebug("Error when trying to bind user, missing username or password. Username::" + uid + " pwd::"
                    + pwd);
        }
        errors.insert("Username and password must be selected");
        return null;
    }

    final LdapContext ctx = bindSystem();
    if (ctx == null) {
        errors.insert("LDAP connection error");
        return null;
    }
    final String userDN = searchUserDN(uid, ctx);
    if (userDN == null) {
        logInfo("Error when trying to bind user with username::" + uid + " - user not found on LDAP server"
                + (LDAPLoginModule.isCacheLDAPPwdAsOLATPwdOnLogin() ? ", trying with OLAT login provider"
                        : ""));
        errors.insert("Username or password incorrect");
        return null;
    }

    // Ok, so far so good, user exists. Now try to fetch attributes using the
    // users credentials
    final Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapUrl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, userDN);
    env.put(Context.SECURITY_CREDENTIALS, pwd);
    if (LDAPLoginModule.isSslEnabled()) {
        enableSSL(env);
    }

    try {
        final Control[] connectCtls = new Control[] {};
        final LdapContext userBind = new InitialLdapContext(env, connectCtls);
        final Attributes attributes = userBind.getAttributes(userDN, userAttr);
        userBind.close();
        return attributes;
    } catch (final AuthenticationException e) {
        logInfo("Error when trying to bind user with username::" + uid + " - invalid LDAP password");
        errors.insert("Username or password incorrect");
        return null;
    } catch (final NamingException e) {
        logError("NamingException when trying to get attributes after binding user with username::" + uid, e);
        errors.insert("Username or password incorrect");
        return null;
    }
}

From source file:org.olat.ldap.manager.LDAPLoginManagerImpl.java

/**
 * /*  w  w w  .j  a va 2s .c  o m*/
 * Connect to LDAP with the User-Name and Password given as parameters
 * 
 * Configuration: LDAP URL = ldapContext.xml (property=ldapURL) LDAP Base =
 * ldapContext.xml (property=ldapBase) LDAP Attributes Map =
 * ldapContext.xml (property=userAttrs)
 * 
 * 
 * @param uid The users LDAP login name (can't be null)
 * @param pwd The users LDAP password (can't be null)
 * 
 * @return After successful bind Attributes otherwise NULL
 * 
 * @throws NamingException
 */
@Override
public Attributes bindUser(String uid, String pwd, LDAPError errors) {
    // get user name, password and attributes
    String ldapUrl = ldapLoginModule.getLdapUrl();
    String[] userAttr = syncConfiguration.getUserAttributes();

    if (uid == null || pwd == null) {
        if (log.isDebug())
            log.debug("Error when trying to bind user, missing username or password. Username::" + uid
                    + " pwd::" + pwd);
        errors.insert("Username and password must be selected");
        return null;
    }

    LdapContext ctx = bindSystem();
    if (ctx == null) {
        errors.insert("LDAP connection error");
        return null;
    }
    String userDN = ldapDao.searchUserDN(uid, ctx);
    if (userDN == null) {
        log.info("Error when trying to bind user with username::" + uid + " - user not found on LDAP server"
                + (ldapLoginModule.isCacheLDAPPwdAsOLATPwdOnLogin() ? ", trying with OLAT login provider"
                        : ""));
        errors.insert("Username or password incorrect");
        return null;
    }

    // Ok, so far so good, user exists. Now try to fetch attributes using the
    // users credentials
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapUrl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, userDN);
    env.put(Context.SECURITY_CREDENTIALS, pwd);
    if (ldapLoginModule.getLdapConnectionTimeout() != null) {
        env.put(TIMEOUT_KEY, ldapLoginModule.getLdapConnectionTimeout().toString());
    }
    if (ldapLoginModule.isSslEnabled()) {
        enableSSL(env);
    }

    try {
        Control[] connectCtls = new Control[] {};
        LdapContext userBind = new InitialLdapContext(env, connectCtls);
        Attributes attributes = userBind.getAttributes(userDN, userAttr);
        userBind.close();
        return attributes;
    } catch (AuthenticationException e) {
        log.info("Error when trying to bind user with username::" + uid + " - invalid LDAP password");
        errors.insert("Username or password incorrect");
        return null;
    } catch (NamingException e) {
        log.error("NamingException when trying to get attributes after binding user with username::" + uid, e);
        errors.insert("Username or password incorrect");
        return null;
    }
}