List of usage examples for javax.naming.directory Attributes get
Attribute get(String attrID);
From source file:com.spotify.helios.authentication.crtauth.LdapKeyProvider.java
@Override public RSAPublicKey getKey(final String username) throws KeyNotFoundException { final List<String> result = ldapTemplate.search(query().base(baseSearchPath).where("uid").is(username), new AttributesMapper<String>() { @Override/*from w w w. ja v a 2s. c o m*/ public String mapFromAttributes(final Attributes attributes) throws NamingException { log.debug("got ldap stuff for uid {}", username); return attributes.get("sshPublicKey").toString(); } }); if (result.isEmpty()) { throw new KeyNotFoundException(); } else if (result.size() == 1) { final String r = result.get(0); RSAPublicKeySpec publicKeySpec; try { final String sshPublicKey = r.replace("sshPublicKey: ", ""); publicKeySpec = TraditionalKeyParser.parsePemPublicKey(sshPublicKey); final KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return (RSAPublicKey) keyFactory.generatePublic(publicKeySpec); } catch (InvalidKeyException | InvalidKeySpecException | NoSuchAlgorithmException e) { e.printStackTrace(); } } throw new IllegalStateException("Found more than one LDAP user for name: " + username); }
From source file:org.jasig.cas.adaptors.ldap.remote.RemoteIpLookupCredentialsToPrincipalResolver.java
protected String extractPrincipalId(final Credentials credentials) { final RemoteAddressCredentials c = (RemoteAddressCredentials) credentials; final String formattedIpAddress = getFormattedIpAddress(c.getRemoteAddress().trim()); if (!StringUtils.hasText(formattedIpAddress)) { return null; }/* ww w. j a va2 s . c om*/ if (log.isDebugEnabled()) { log.debug("Original IP address: " + c.getRemoteAddress()); log.debug("Formatted IP address: " + formattedIpAddress); } final String attributeId = getAttributeIds()[0]; final List principalList = this.getLdapTemplate().search(getSearchBase(), LdapUtils.getFilterWithValues(getFilter(), formattedIpAddress), getSearchControls(), new AttributesMapper() { public Object mapFromAttributes(final Attributes attrs) throws NamingException { final Attribute attribute = attrs.get(attributeId); return attribute == null ? null : 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 \"" + getFilter() + "\", " + "which is not allowed."); return null; } return (String) principalList.get(0); }
From source file:jenkins.security.plugins.ldap.FromUserRecordLDAPGroupMembershipStrategy.java
@Override public GrantedAuthority[] getGrantedAuthorities(LdapUserDetails ldapUser) { List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(); Attributes attributes = ldapUser.getAttributes(); final String attributeName = getAttributeName(); Attribute attribute = attributes == null ? null : attributes.get(attributeName); if (attribute != null) { try {/*from w w w. j a va 2s .co m*/ for (Object value : Collections.list(attribute.getAll())) { String groupName = String.valueOf(value); try { LdapName dn = new LdapName(groupName); groupName = String.valueOf(dn.getRdn(dn.size() - 1).getValue()); } catch (InvalidNameException e) { LOGGER.log(Level.FINEST, "Expected a Group DN but found: {0}", groupName); } result.add(new GrantedAuthorityImpl(groupName)); } } catch (NamingException e) { LogRecord lr = new LogRecord(Level.FINE, "Failed to retrieve member of attribute ({0}) from LDAP user details"); lr.setThrown(e); lr.setParameters(new Object[] { attributeName }); LOGGER.log(lr); } } return result.toArray(new GrantedAuthority[result.size()]); }
From source file:com.globalsight.everest.usermgr.UserLdapHelper.java
/** * Get the Uset ID array from a NamingEnumeration *//*from w w w . j a va 2s.com*/ static Vector getUIDsVectorFromSearchResults(NamingEnumeration p_SearchResults) throws NamingException { Vector uids = new Vector(); while (p_SearchResults.hasMoreElements()) { /* Next directory entry */ Object searchResultObj = p_SearchResults.nextElement(); if (searchResultObj instanceof SearchResult) { SearchResult tempSearchResult = (SearchResult) searchResultObj; Attributes entry = tempSearchResult.getAttributes(); String uid = getSingleAttributeValue(entry.get(LDAP_ATTR_USERID)); uids.addElement(uid); } } p_SearchResults.close(); return uids; }
From source file:com.surevine.chat.auth.GroupAuthorisationFilter.java
/** * Get a list of the members of a group, searching for the group using an * LDAP filter expression and scope.//from w w w. j a v a2 s . c o m * * @param filter * LDAP search filter (see RFC2254) * @param scope * One of SearchControls.OBJECT_SCOPE, * SearchControls.ONELEVEL_SCOPE, or SearchControls.SUBTREE_SCOPE * (see javax.naming.directory.SearchControls) * @return List of usernames * @throws NamingException * @throws LdapException * On any LDAP error */ private Collection<String> getGroupMembers(final String groupName) throws NamingException { _logger.debug("Looking for members of " + groupName); String filter = "cn=" + groupName; Collection<String> memberList = new HashSet<String>(20); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> objects; DirContext ctx = getLdapConnection(); objects = ctx.search("ou=groups", filter, controls); while (objects.hasMore()) { SearchResult sr = (SearchResult) objects.next(); Attributes attributes = sr.getAttributes(); Attribute attribute = attributes.get("member"); if (attribute != null) { NamingEnumeration<?> valueEnum = attribute.getAll(); while (valueEnum.hasMore()) { String value = valueEnum.next().toString(); final String searchFor = "cn="; int start = value.indexOf(searchFor); int end = value.indexOf(',', start); if (start >= 0 && end >= 0) { String name = value.substring(start + searchFor.length(), end); _logger.debug(name + " is a chatter"); memberList.add(name); } } } } _logger.debug("Returning a total of " + memberList.size() + " chatters"); return memberList; }
From source file:com.globalsight.everest.usermgr.UserLdapHelper.java
/** * Get the company names from a NamingEnumeration *//* w ww . j a v a 2s . com*/ static String[] getCompanyNamesFromSearchResults(NamingEnumeration p_searchResults) throws NamingException { // use a set so duplicates are not saved Set companyNames = new TreeSet(); while (p_searchResults.hasMoreElements()) { String cName = null; Object searchResultObj = p_searchResults.nextElement(); if (searchResultObj instanceof SearchResult) { SearchResult tempSearchResult = (SearchResult) searchResultObj; Attributes entry = tempSearchResult.getAttributes(); cName = getSingleAttributeValue(entry.get(LDAP_ATTR_COMPANY)); } if (cName != null && cName.trim().length() > 0) { // adds it to the set // if it already exists just returns (NOP) companyNames.add(cName); } } p_searchResults.close(); String[] cns = new String[companyNames.size()]; return (String[]) companyNames.toArray(cns); }
From source file:com.globalsight.everest.usermgr.UserLdapHelper.java
static Vector getNamesVectorFromSearchResults(NamingEnumeration p_SearchResults) throws NamingException { Vector userNames = new Vector(); while (p_SearchResults.hasMoreElements()) { /* Next directory entry */ Object searchResultObj = p_SearchResults.nextElement(); if (searchResultObj instanceof SearchResult) { SearchResult tempSearchResult = (SearchResult) searchResultObj; Attributes entry = tempSearchResult.getAttributes(); String userName = getSingleAttributeValue(entry.get(LDAP_ATTR_USER_NAME)); userNames.addElement(userName); }// ww w . ja v a2s. co m } p_SearchResults.close(); return userNames; }
From source file:org.apache.james.user.ldap.ReadOnlyLDAPGroupRestriction.java
/** * Extracts the DNs for members of the group with the given LDAP context * attributes. This is achieved by extracting all the values of the LDAP * attribute, with name equivalent to the field value * {@link #memberAttribute}, from the attributes collection. * * @param groupAttributes The attributes taken from the group's LDAP context. * @return A collection of distinguished-names for the users belonging to * the group with the specified attributes. * @throws NamingException Propagated from underlying LDAP communication layer. *//* ww w.ja va 2 s.c o m*/ private Collection<String> extractMembers(Attributes groupAttributes) throws NamingException { Collection<String> result = new ArrayList<String>(); Attribute members = groupAttributes.get(memberAttribute); NamingEnumeration<?> memberDNs = members.getAll(); while (memberDNs.hasMore()) result.add(memberDNs.next().toString()); return result; }
From source file:com.globalsight.everest.usermgr.UserLdapHelper.java
/** * Convert a Attributes to a UserInfo object. *//*from w w w. j a va 2 s . c o m*/ static UserInfo getUserInfoFromLDAPEntry(Attributes p_entry) throws NamingException { UserInfo ui = new UserInfo(); Attribute attr = p_entry.get(LDAP_ATTR_USERID); ui.setUserId(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_USER_NAME); ui.setUserName(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_TITLE); ui.setTitle(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_FIRST_NAME); ui.setFirstName(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_LAST_NAME); ui.setLastName(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_EMAIL); ui.setEmailAddress(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_CC_EMAIL); ui.setCCEmailAddress(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_BCC_EMAIL); ui.setBCCEmailAddress(getSingleAttributeValue(attr)); attr = p_entry.get(LDAP_ATTR_INALLPROJECTS); if (attr != null && getSingleAttributeValue(attr).equalsIgnoreCase(LDAP_ATTR_TRUE)) { // set to "false" as default - so only need to set to true // if value is "true" ui.isInAllProjects(true); } return ui; }
From source file:org.sonar.plugins.ldap.LdapAutodiscovery.java
List<LdapSrvRecord> getLdapServers(DirContext context, String domain) throws NamingException { Attributes lSrvAttrs = context.getAttributes("dns:/_ldap._tcp." + domain, new String[] { "srv" }); Attribute serversAttribute = lSrvAttrs.get("srv"); NamingEnumeration<?> lEnum = serversAttribute.getAll(); SortedSet<LdapSrvRecord> result = new TreeSet<>(); while (lEnum.hasMore()) { String srvRecord = (String) lEnum.next(); // priority weight port target String[] srvData = srvRecord.split(" "); int priority = NumberUtils.toInt(srvData[0]); int weight = NumberUtils.toInt(srvData[1]); String port = srvData[2]; String target = srvData[3]; if (target.endsWith(".")) { target = target.substring(0, target.length() - 1); }/* w w w .ja v a 2 s . c o m*/ String server = "ldap://" + target + ":" + port; result.add(new LdapSrvRecord(server, priority, weight)); } return new ArrayList<>(result); }