Example usage for javax.naming.directory Attributes get

List of usage examples for javax.naming.directory Attributes get

Introduction

In this page you can find the example usage for javax.naming.directory Attributes get.

Prototype

Attribute get(String attrID);

Source Link

Document

Retrieves the attribute with the given attribute id from the attribute set.

Usage

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

/**
 * Check if connection with login and password possible.
 *
 * @param inBenutzer/*from   w  ww . ja  v  a2s . com*/
 *            User object
 * @param inPasswort
 *            String
 * @return Login correct or not
 */
public boolean isUserPasswordCorrect(User inBenutzer, String inPasswort) {
    logger.debug("start login session with ldap");
    Hashtable<String, String> env = getLdapConnectionSettings();

    // Start TLS
    if (ConfigCore.getBooleanParameter("ldap_useTLS", false)) {
        logger.debug("use TLS for auth");
        env = new Hashtable<>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ConfigCore.getParameter("ldap_url"));
        env.put("java.naming.ldap.version", "3");
        LdapContext ctx = null;
        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, getUserDN(inBenutzer));
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, inPasswort);
            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 {
            if (tls != null) {
                try {
                    // Tear down TLS connection
                    tls.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
            if (ctx != null) {
                try {
                    // Close LDAP connection
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(e);
                }
            }
        }
    } else {
        logger.debug("don't use TLS for auth");
        if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) {
            env.put(Context.SECURITY_AUTHENTICATION, "none");
            // TODO auf passwort testen
        } else {
            env.put(Context.SECURITY_PRINCIPAL, getUserDN(inBenutzer));
            env.put(Context.SECURITY_CREDENTIALS, inPasswort);
        }
        logger.debug("ldap environment set");

        try {
            if (logger.isDebugEnabled()) {
                logger.debug("start classic ldap authentification");
                logger.debug("user DN is " + getUserDN(inBenutzer));
            }

            if (ConfigCore.getParameter("ldap_AttributeToTest") == null) {
                logger.debug("ldap attribute to test is null");
                DirContext ctx = new InitialDirContext(env);
                ctx.close();
                return true;
            } else {
                logger.debug("ldap attribute to test is not null");
                DirContext ctx = new InitialDirContext(env);

                Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer));
                Attribute la = attrs.get(ConfigCore.getParameter("ldap_AttributeToTest"));
                logger.debug("ldap attributes set");
                String test = (String) la.get(0);
                if (test.equals(ConfigCore.getParameter("ldap_ValueOfAttribute"))) {
                    logger.debug("ldap ok");
                    ctx.close();
                    return true;
                } else {
                    logger.debug("ldap not ok");
                    ctx.close();
                    return false;
                }
            }
        } catch (NamingException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("login not allowed for " + inBenutzer.getLogin(), e);
            }
            return false;
        }
    }
}

From source file:egovframework.com.ext.ldapumt.service.impl.ObjectMapper.java

/**
 * ContextAdapter?  ? vo .//  w  ww  .j  a v a2 s.c  o m
 */
public Object mapFromContext(Object arg0) throws NamingException {
    DirContextAdapter adapter = (DirContextAdapter) arg0;
    Attributes attrs = adapter.getAttributes();

    LdapObject vo = null;

    try {
        vo = (LdapObject) type.newInstance();
    } catch (Exception e2) {
        throw new RuntimeException(e2);
    }

    vo.setDn(adapter.getDn().toString());

    BeanInfo beanInfo;
    try {
        beanInfo = Introspector.getBeanInfo(type);
    } catch (IntrospectionException e1) {
        throw new RuntimeException(e1);
    }

    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

    for (PropertyDescriptor descriptor : propertyDescriptors) {
        if (attrs.get(descriptor.getName()) != null)
            try {
                Class<?> o = descriptor.getPropertyType();
                if (o == int.class)
                    PropertyUtils.setProperty(vo, descriptor.getName(),
                            Integer.valueOf((String) attrs.get(descriptor.getName()).get()));
                if (o == String.class)
                    PropertyUtils.setProperty(vo, descriptor.getName(),
                            (String) attrs.get(descriptor.getName()).get());
                if (o == Boolean.class)
                    PropertyUtils.setProperty(vo, descriptor.getName(),
                            ((String) attrs.get(descriptor.getName()).get()).equals("Y"));

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
    }

    return vo;
}

From source file:org.viafirma.nucleo.validacion.CRLUtil.java

/**
 * Se conecta a la url indicada y se descarga las crls. No se esta usando
 * *******************!!! En desarrollo, no funciona
 * //from w  w w  .  ja v a 2s.  co m
 * @param hostURL
 * @return
 * @throws CRLException
 *             No se ha podido recuperar el listado
 * @throws CertificateParsingException
 */
@SuppressWarnings("unchecked")
private InputStream getIoCrlFromFNMTLDAP(X509Certificate certificadoX509)
        throws CRLException, CertificateParsingException {
    // ************************
    // recupero las propiedades para realizar la busqueda en LDAP.
    // EJ :[CN=CRL1, OU=FNMT Clase 2 CA, O=FNMT, C=ES] {2.5.4.11=FNMT Clase
    // 2 CA, 2.5.4.10=FNMT, 2.5.4.6=ES, 2.5.4.3=CRL1}
    Map<String, String> propiedades = new HashMap<String, String>();
    try {
        log.debug("Recuperando puntos de distribucin CRL del certificado FNMT: "
                + certificadoX509.getIssuerDN());
        // recupero la extensin OID 2.5.29.31 ( id-ce-cRLDistributionPoinds
        // segun el RFC 3280 seccin 4.2.1.14)
        byte[] val1 = certificadoX509.getExtensionValue(OID_CRLS);
        if (val1 == null) {
            log.debug("   El certificado NO tiene punto de distribucin de CRL ");
        } else {
            ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(val1));
            DERObject derObj = oAsnInStream.readObject();
            DEROctetString dos = (DEROctetString) derObj;
            byte[] val2 = dos.getOctets();
            ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(val2));
            DERObject derObj2 = oAsnInStream2.readObject();

            X509Handler.getCurrentInstance().readPropiedadesOid(OID_CRLS, derObj2, propiedades);

        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new CertificateParsingException(e.toString());
    }

    // comprobamos la configuracin
    if (isSomeFNMTValorNull()) {
        throw new CRLException(
                "Para el acceso a las CRLs de la FNMT es necesario las credenciales. Indique el parametro de configuracin :"
                        + Constantes.CONEXION_LDAP_CRL_FNMT);
    }

    String CN = "CN=" + propiedades.get(FNMT_CN_IDENTIFICADOR) + "," + certificadoX509.getIssuerDN();
    log.debug("Buscando en el LDAP " + CN);

    // **********************************************
    // Nos conectamos al LDAP para recuperar la CRLs.

    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, fnmtLDAPHostURL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, fnmtPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, fnmtCredencial);
    env.put(Context.REFERRAL, "follow");

    try {
        DirContext ctx = new InitialDirContext(env);
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        NamingEnumeration namings = (ctx.search(CN, "(objectclass=*)", searchControls));

        log.debug("Se ha logrado conectar al LDAP");

        if (namings.hasMore()) {
            log.debug("Recuperando el contenido de la CRLs");
            // recupero el resultado
            SearchResult resultado = ((SearchResult) namings.next());

            // recupero todos los atributos del resultado
            Attributes avals = resultado.getAttributes();

            // recupero los bytes.
            byte[] bytes;
            if ((avals.get("certificateRevocationList;binary")) != null) {
                log.debug("Atributos deben estar en binario");
                Attribute atributo = (avals.get("certificateRevocationList;binary"));
                bytes = ((byte[]) atributo.get());
            } else {
                log.debug("Atributos en exadecimal En Hexadecimal");
                Attribute atributo = (avals.get("certificateRevocationList"));
                bytes = ((byte[]) atributo.get());
                log.debug("Por implementar");
            }

            if (bytes != null) {
                ByteArrayInputStream io = new ByteArrayInputStream(bytes);
                return io;
            }
        }
    } catch (NamingException e) {
        log.error("No se puede conectar al LDAP!!", e);
    }
    return null;
}

From source file:com.swdouglass.joid.server.DirectoryUserManagerImpl.java

@Override
public User getUser(String username) {
    User user = null;//from w  ww.  ja  va2 s . c om
    try {
        Attributes attrs = findAttributes(username, initialCtx);
        if (attrs != null) {
            if (log.isDebugEnabled()) {
                NamingEnumeration ne = attrs.getAll();
                while (ne.hasMore()) {
                    log.debug(ne.next());
                }
            }
            // create the user, password very likely to be in binary form...
            user = new User(username, DirectoryUtil.getAttributeValue(attrs, PASSWORD_ATTRIBUTE_PROP,
                    PASSWORD_ATTRIBUTE_PROP_DEFAULT));

            // set the list of OpenIDs
            Attribute openIDattr = attrs
                    .get(DirectoryUtil.getProperty(OPENID_OBJECTCLASS_PROP, OPENID_OBJECTCLASS_PROP_DEFAULT));
            Enumeration e = openIDattr.getAll();
            Set<String> openIDs = new HashSet<String>();
            while (e.hasMoreElements()) {
                openIDs.add((String) e.nextElement());
            }
            user.setOpenIDs(openIDs);
        }
    } catch (NamingException ex) {
        log.warn("Error in finding the userame=" + username, ex);
    }
    return user;
}

From source file:eu.europa.ec.markt.dss.validation102853.https.CommonDataLoader.java

/**
 * This method retrieves data using LDAP protocol.
 * - CRL from given LDAP url, e.g. ldap://ldap.infonotary.com/dc=identity-ca,dc=infonotary,dc=com
 *
 * @param urlString//  ww  w  .  j a  v  a  2s  .  c om
 * @return
 */
private byte[] ldapGet(final String urlString) {

    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, urlString);
    try {

        final DirContext ctx = new InitialDirContext(env);
        final Attributes attributes = ctx.getAttributes("");
        final javax.naming.directory.Attribute attribute = attributes.get("certificateRevocationList;binary");
        final byte[] ldapBytes = (byte[]) attribute.get();
        if (ldapBytes == null || ldapBytes.length == 0) {
            throw new DSSException("Cannot download CRL from: " + urlString);
        }
        return ldapBytes;
    } catch (Exception e) {
        LOG.warn(e.getMessage(), e);
    }
    return null;
}

From source file:ca.tnt.ldaputils.impl.LdapEntry.java

/**
 * Updates the specified attribute from LDAP.
 * <p/>/*from w  w w.ja va  2 s  .com*/
 * MINOR : Instead of using LDAPFactory.getAttributes, using
 * DirContext.getAttributes().  Then we can remove the getAttributes().
 * <p/>
 * CRITICAL reload the attribute using the reflection framework somehow.
 *
 * @param attrName the name of the attribute
 *
 * @throws NamingException if any LDAP errors occur.
 */
protected void updateAttribute(final String attrName) throws NamingException {
    final String[] returningAttributes;
    final Attributes returnedAttributes;

    returningAttributes = new String[1];
    returningAttributes[0] = attrName;
    returnedAttributes = manager.getAttributes(getDn(), returningAttributes);

    if (returnedAttributes.size() == 1) { // only attempt to load the attributes if the search found them.
                                          // the attribute to update
        attributes.put(returnedAttributes.get(attrName));
    }
}

From source file:com.funambol.LDAP.dao.impl.ContactDAO.java

public String getRdnValue(Attributes attrs) {
    String ret = null;/*  ww  w. j  a v  a 2  s  .  c  o  m*/
    if (attrs != null) {
        ret = LdapUtils.getPrintableAttribute(attrs.get(getRdnAttribute()));
    }
    return ret;
}

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

/**
 * Given a userDN, this method retrieves the user attributes from the LDAP
 * server, so as to extract the items that are of interest to James.
 * Specifically it extracts the userId, which is extracted from the LDAP
 * attribute whose name is given by the value of the field
 * {@link #userIdAttribute}./*  w  w  w  . ja v  a 2s .  c om*/
 *
 * @param userDN
 *            The distinguished-name of the user whose details are to be
 *            extracted from the LDAP repository.
 * @return A {@link ReadOnlyLDAPUser} instance which is initialized with the
 *         userId of this user and ldap connection information with which
 *         the userDN and attributes were obtained.
 * @throws NamingException
 *             Propagated by the underlying LDAP communication layer.
 */
private ReadOnlyLDAPUser buildUser(String userDN) throws NamingException {
    Attributes userAttributes = ldapContext.getAttributes(userDN);
    Attribute userName = userAttributes.get(userIdAttribute);
    return new ReadOnlyLDAPUser(userName.get().toString(), userDN, ldapContext);
}

From source file:com.aurel.track.util.LdapUtil.java

/**
 * Get all ldap groups//  w ww. j  av a 2  s. c  o m
 * 
 * @param siteBean
 * @param baseDnGroup
 * @param ldapFilterGroups
 * @param groupAttributeName
 * @param groupToMemberReferencesMap
 * @return
 * @throws Exception
 */
public static Map<String, TPersonBean> getLdapGroupsPaged(String baseURL, TSiteBean siteBean,
        String baseDnGroup, String ldapFilterGroups, String groupAttributeName,
        Map<String, List<String>> groupToMemberReferencesMap) throws Exception {
    if (ldapFilterGroups == null || "".equals(ldapFilterGroups) || "*".equals(ldapFilterGroups)) {
        ldapFilterGroups = "(" + groupAttributeName + "=*)";
    }
    String bindDN = siteBean.getLdapBindDN();
    String bindPassword = siteBean.getLdapBindPassword();
    LdapContext context = getInitialContext(baseURL + baseDnGroup, bindDN, bindPassword);
    HashMap<String, TPersonBean> ldapGroupsMap = new HashMap<String, TPersonBean>();
    if (context == null) {
        LOGGER.warn("Context is null");
        return ldapGroupsMap;
    }
    int recordCount = 0;
    SearchControls ctls = null;
    String groupMemberAttributName = ldapMap.get(LDAP_CONFIG.GROUP_MEMBER);
    if (groupMemberAttributName == null) {
        groupMemberAttributName = DEFAULT_GROUP_MEMBER;
    }
    try {
        // Activate paged results
        int pageSize = 5;
        byte[] cookie = null;
        context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
        int total;
        // Control the search
        ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers()
                + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can handle
                                                                                                                                                                     // anyways
        do {
            /* perform the search */
            NamingEnumeration<SearchResult> results = context.search("", ldapFilterGroups, ctls);
            /* for each entry print out name + all attrs and values */
            while (results != null && results.hasMore()) {
                SearchResult searchResult = (SearchResult) results.next();
                // Attributes atrs = sr.getAttributes();
                Attributes attributes = searchResult.getAttributes();
                if (attributes == null) {
                    LOGGER.warn("No attributes found in LDAP search result " + searchResult.getName());
                    return null;
                }
                TPersonBean personBean = new TPersonBean();
                try {
                    Attribute groupNameAttribute = attributes.get(groupAttributeName);
                    if (groupNameAttribute != null) {
                        String groupName = (String) groupNameAttribute.get();
                        LOGGER.debug("Groupname: " + groupName);
                        if (groupName == null || "".equals(groupName)) {
                            LOGGER.info("No value for group name attribute " + groupAttributeName);
                            return null;
                        } else {
                            personBean.setLoginName(groupName);
                            ldapGroupsMap.put(personBean.getLoginName(), personBean);
                        }
                        Attribute memberAttribute = attributes.get(groupMemberAttributName);
                        if (memberAttribute != null) {
                            NamingEnumeration<?> members = memberAttribute.getAll();
                            while (members != null && members.hasMore()) {
                                String memberSearchResult = (String) members.next();
                                List<String> memberDNList = groupToMemberReferencesMap.get(groupName);
                                if (memberDNList == null) {
                                    memberDNList = new ArrayList<String>();
                                    groupToMemberReferencesMap.put(groupName, memberDNList);
                                }
                                memberDNList.add(memberSearchResult);
                            }
                        } else {
                            LOGGER.info("Could not find value(s) for group member attribute "
                                    + groupMemberAttributName + " for group " + groupName);
                        }
                    }
                    LOGGER.debug("LDAP entry cn: " + (String) attributes.get("cn").get());
                    LOGGER.debug("Processed " + personBean.getLoginName() + " (" + personBean.getFirstName()
                            + " " + personBean.getLastName() + ")");
                } catch (Exception e) {
                    LOGGER.warn("Problem setting attributes from LDAP: " + e.getMessage());
                    LOGGER.warn(
                            "This is probably a configuration error in the LDAP mapping section of quartz-jobs.xml");
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Stack trace:", e);
                    }
                }
                ++recordCount;
            }
            // Examine the paged results control response
            Control[] controls = context.getResponseControls();
            if (controls != null) {
                for (int i = 0; i < controls.length; i++) {
                    if (controls[i] instanceof PagedResultsResponseControl) {
                        PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                        total = prrc.getResultSize();
                        if (total != 0) {
                            LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total
                                    + ") *****************\n");
                        } else {
                            LOGGER.debug(
                                    "***************** END-OF-PAGE " + "(total: unknown) ***************\n");
                        }
                        cookie = prrc.getCookie();
                    }
                }
            } else {
                LOGGER.debug("No controls were sent from the server");
            }
            // Re-activate paged results
            context.setRequestControls(
                    new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });

        } while (cookie != null);
    } catch (SizeLimitExceededException sle) {
        if (recordCount < ctls.getCountLimit()) {
            LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server.");
            LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with "
                    + sle.getMessage());
            LOGGER.error(
                    "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter.");
        } else {
            LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server ("
                    + recordCount + ").");
            LOGGER.error(
                    "You have to get more user licenses for Genji or specify a more suitable search base or filter.");
        }
        LOGGER.error("The LDAP synchronization is most likely incomplete.");
    } catch (NamingException e) {
        LOGGER.error("PagedSearch failed.");
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    } catch (IOException ie) {
        LOGGER.error("PagedSearch failed.");
        LOGGER.debug(ExceptionUtils.getStackTrace(ie));
    } finally {
        context.close();
    }
    return ldapGroupsMap;
}

From source file:ldap.ActiveLoginImpl.java

public Attributes hashPasswordAttribute(Attributes account) throws NamingException {
    Attribute pwdAtt = account.get(LdapConstants.ldapAttrUserPassword);
    if (pwdAtt == null || pwdAtt.get() == null)
        throw new NamingException("user password attribute missing!");

    logger.info("entered hashPassword()" + pwdAtt);
    Object o = pwdAtt.get();/*from  w ww. j  a  v  a 2s.  co m*/
    logger.info("entered hashPassword()");
    byte[] hash = hashPassword(o);
    logger.info("completed hashPassword()");

    account.remove(LdapConstants.ldapAttrUserPassword);
    logger.info("adding the ldapAttrUserPassword, " + hash);
    account.put(LdapConstants.ldapAttrUserPassword, hash);
    byte[] pwd = (byte[]) account.get("userPassword").get();
    if (pwd != null) {
        logger.info("getting the ldapAttrUserPassword, " + pwd);
    } else {
        logger.info("hash pwd is null when tried to retrieve it");
    }
    return account;
}