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.interseroh.report.test.security.LdapServerTest.java

@Test
public void testJndiSun() throws NamingException {
    Hashtable<String, String> contextParams = new Hashtable<String, String>();
    contextParams.put(Context.PROVIDER_URL, "ldap://ldap.xxx:389");
    contextParams.put(Context.SECURITY_PRINCIPAL, USER_LDAP);
    contextParams.put(Context.SECURITY_CREDENTIALS, PASSWORD_LDAP);
    contextParams.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    DirContext dirContext = new InitialDirContext(contextParams);

    Attributes attributes = dirContext.getAttributes("", new String[] { "namingContexts" });
    Attribute attribute = attributes.get("namingContexts");
    NamingEnumeration<?> all = attribute.getAll();
    while (all.hasMore()) {
        String next = (String) all.next();
        logger.info(next);//ww w  .j  a v a 2  s.  c o  m
    }
}

From source file:org.jasig.ssp.service.impl.LdapPersonAttributesService.java

private String extractProperty(final Attributes attrs, final String property) {
    final Attribute attrib = attrs.get(property);
    if (null == attrib) {
        return null;
    } else {//  w w w  .ja  va  2  s .  c o m
        Object val;
        try {
            val = attrib.get();
        } catch (NamingException e) {
            return null;
        }

        try {
            return (String) val;
        } catch (ClassCastException cce) {
            return val.toString();
        }
    }
}

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

/**
 * Convert a Attributes to a EmailInformation object.
 *///from   w w w  . j  a  v a  2  s.  c om
private static EmailInformation getUserEmailInfo(Attributes p_entry) throws NamingException {

    Attribute attr = p_entry.get(LDAP_ATTR_USERID);
    String userId = getSingleAttributeValue(attr);

    return getUserEmailInfo(userId, p_entry);
}

From source file:nl.knaw.dans.common.ldap.repo.AbstractLdapUserRepo.java

/**
 * Note that {@link User.getPassword()} will not give the password from the repository after 'unmarshalling'.
 * The user repository must be queried for this because the password is never retrieved from the repository 
 * and the User object does not contain it.  
 * /*from   ww  w  .  j  a  v a  2  s . com*/
 */
public boolean isPasswordStored(String userId) throws RepositoryException {
    if (StringUtils.isBlank(userId)) {
        logger.debug("Insufficient data for getting user info.");
        throw new IllegalArgumentException();
    }
    String filter = "(&(objectClass=" + getObjectClassName() + ")(uid=" + userId + "))";

    final String PASSWD_ATTR_NAME = "userPassword";
    boolean passwordStored = false;
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setCountLimit(1);
    ctls.setReturningAttributes(new String[] { "uid", PASSWD_ATTR_NAME });

    try {
        NamingEnumeration<SearchResult> resultEnum = getClient().search(getContext(), filter, ctls);
        while (resultEnum.hasMoreElements()) {
            SearchResult result = resultEnum.next();
            Attributes attrs = result.getAttributes();
            if (attrs.get(PASSWD_ATTR_NAME) != null)
                passwordStored = true;
        }
    } catch (NamingException e) {
        throw new RepositoryException(e);
    }

    return passwordStored;
}

From source file:nl.surfnet.coin.ldap.LdapClientImpl.java

/**
 * Save get of an Attribute value, may return null
 * @param attrID the attribute id/*w w  w .j av  a 2 s  .c o m*/
 * @param attributes the attributes holder to get it from
 * @return the stringified attribute or null.
 */
private String getAttribute(String attrID, Attributes attributes) {
    Attribute attribute = attributes.get(attrID);
    try {
        return attribute != null ? (String) attribute.get() : null;
    } catch (NamingException e) {
        // ignore this as we can't recover
        return null;
    }
}

From source file:org.jasig.schedassist.impl.oraclecalendar.OracleCalendarResourceAccountAttributesMapper.java

/**
 * Get the specified attribute, or null.
 * If the attribute is not empty, it's value is {@link String#trim()}'d.
 * //from   w  w  w .j a v  a  2s . c o  m
 * @param attributes
 * @param attributeName
 * @return
 * @throws NamingException 
 */
String getAttributeValue(Attributes attributes, String attributeName) throws NamingException {
    Attribute attribute = attributes.get(attributeName);
    if (null != attribute) {
        String value = (String) attribute.get();
        if (null != value) {
            value = value.trim();
        }
        return value;
    }
    return null;
}

From source file:py.una.pol.karaku.util.LDAPUtil.java

/**
 * Recupera los usuarios de LDAP/*  ww  w . jav  a 2s  .c o m*/
 * 
 * @return Una lista con los usuarios de LDAP
 */
public List<User> getUsers() {

    List<User> users = new ArrayList<User>();

    try {
        DirContext ctx = createInitialDirContext();

        Attributes matchAttrs = new BasicAttributes(true);
        matchAttrs.put(new BasicAttribute("uid"));

        NamingEnumeration<SearchResult> answer = ctx.search("ou=users", matchAttrs);

        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            String uid = sr.getName().substring(4);
            // No se retornan los usuarios especiales
            if (!uid.startsWith(LDAP_SPECIAL_USER_PREFIX) && !ListHelper.contains(EXCLUDED_USERS, uid)) {
                User user = new User();
                user.setUid(uid);
                Attributes atributos = sr.getAttributes();
                String cn = atributos.get("cn").toString().substring(4);
                user.setCn(cn);
                users.add(user);
            }
        }

    } catch (NamingException e) {
        throw new KarakuRuntimeException(e.getMessage(), e);
    }

    return users;

}

From source file:net.officefloor.plugin.jndi.ldap.CredentialStoreTest.java

/**
 * Ensure able to obtain credentials./*from   w  w  w . j  a  v a2  s .co  m*/
 */
public void testObtainCredentials() throws Exception {

    final Charset ASCII = Charset.forName("ASCII");

    // Calculate the expected credential
    String expectedRaw = "daniel:officefloor:password";
    MessageDigest digest = MessageDigest.getInstance("MD5");
    digest.update(expectedRaw.getBytes(ASCII));
    byte[] expectedBytes = digest.digest();
    String expectedCredentials = Base64.encodeBase64String(expectedBytes).trim();

    // Obtain the context
    DirContext context = this.ldap.getDirContext();

    // Obtain the People context
    DirContext people = (DirContext) context.lookup("ou=People,dc=officefloor,dc=net");
    assertNotNull("Should have People context", people);

    // Search for person
    NamingEnumeration<SearchResult> results = people.search("", "(&(objectClass=inetOrgPerson)(uid=daniel))",
            null);
    assertTrue("Expecting to find daniel entry", results.hasMore());
    SearchResult result = results.next();
    assertFalse("Should only have the daniel entry", results.hasMore());

    // Obtain the digest MD5 credentials for Daniel
    String digestMd5Credential = null;
    Attributes attributes = result.getAttributes();
    Attribute passwordAttribute = attributes.get("userPassword");
    for (NamingEnumeration<?> enumeration = passwordAttribute.getAll(); enumeration.hasMore();) {
        byte[] credentials = (byte[]) enumeration.next();
        String text = new String(credentials, ASCII);

        // Determine if MD5 credential
        if (text.toUpperCase().startsWith("{MD5}")) {
            // Found MD5 credential
            digestMd5Credential = text.substring("{MD5}".length());
        }
    }
    assertNotNull("Must have digest MD5 credential", digestMd5Credential);

    // Ensure correct credentials
    assertEquals("Incorrect DIGEST MD5 credentials", expectedCredentials, digestMd5Credential);
}

From source file:org.jasig.cas.authentication.principal.CredentialsToLDAPAttributePrincipalResolver.java

private String resolveFromLDAP(final String lookupAttributeValue) {
    final String searchFilter = LdapUtils.getFilterWithValues(getFilter(), lookupAttributeValue);

    if (log.isDebugEnabled()) {
        log.debug("LDAP search with filter \"" + searchFilter + "\"");
    }/*from ww  w.  ja  v  a  2  s  .  c o  m*/

    try {
        // searching the directory
        final String idAttribute = getAttributeIds()[0];
        final List principalList = getLdapTemplate().search(getSearchBase(), searchFilter, getSearchControls(),

                new AttributesMapper() {
                    public Object mapFromAttributes(final Attributes attrs) throws NamingException {
                        final Attribute attribute = attrs.get(idAttribute);
                        if (attribute == null) {
                            log.debug("Principal attribute \"" + idAttribute + "\" "
                                    + "not found in LDAP search results. Returning null.");
                            return null;
                        }
                        return attribute.get();
                    }

                });
        if (principalList.isEmpty()) {
            log.debug("LDAP search returned zero results.");
            return null;
        }
        if (principalList.size() > 1) {
            log.error("LDAP search returned multiple results " + "for filter \"" + searchFilter + "\", "
                    + "which is not allowed.");

            return null;
        }
        return (String) principalList.get(0);

    } catch (final Exception e) {
        log.error(e.getMessage(), e);
        return null;
    }
}

From source file:org.cloudfoundry.identity.uaa.ldap.PasswordComparisonAuthenticator.java

public DirContextOperations localCompareAuthenticate(DirContextOperations user, String password) {
    boolean match = false;
    try {/*from  www  . j a  va2  s. co m*/
        Attributes attributes = user.getAttributes();
        Attribute attr = attributes.get(getPasswordAttributeName());
        if (attr.size() == 0) {
            throw new AuthenticationCredentialsNotFoundException(
                    "Missing " + getPasswordAttributeName() + " attribute.");
        }
        for (int i = 0; (attr != null) && (!match) && (i < attr.size()); i++) {
            Object valObject = attr.get(i);
            if (valObject != null && valObject instanceof byte[]) {
                if (passwordEncoder instanceof DynamicPasswordComparator) {
                    byte[] received = password.getBytes();
                    byte[] stored = (byte[]) valObject;
                    match = ((DynamicPasswordComparator) passwordEncoder).comparePasswords(received, stored);
                } else {
                    String encodedPassword = passwordEncoder.encodePassword(password, null);
                    byte[] passwordBytes = Utf8.encode(encodedPassword);
                    match = Arrays.equals(passwordBytes, (byte[]) valObject);
                }
            }
        }
    } catch (NamingException e) {
        throw new BadCredentialsException("Bad credentials", e);
    }
    if (!match)
        throw new BadCredentialsException("Bad credentials");
    return user;
}