ctx.setRequestControls(searchControl); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE); while (answer.hasMoreElements()) { Attributes attributes = ((SearchResult) answer.next()).getAttributes(); String groupName = (String) attributes.get(manager.getGroupNameField()).get(); String description = ""; int elements = 0; try { description = ((String) attributes.get(manager.getGroupDescriptionField()).get()); } catch (NullPointerException e) { Attribute memberField = attributes.get(manager.getGroupMemberField()); if (memberField != null) { NamingEnumeration ne = memberField.getAll(); while (ne.hasMore()) { ne.next(); elements = elements + 1;
roleNames = new LinkedHashSet<String>(); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); log.debug("Retrieving group names for user [" + sr.getName() + "]"); Attributes attrs = sr.getAttributes(); NamingEnumeration ae = attrs.getAll(); while (ae.hasMore()) { Attribute attr = (Attribute) ae.next(); if (attr.getID().equals("memberOf")) {
@Override public void clearCredentials() throws RealmUnavailableException { try { Attributes attributes = new BasicAttributes(); attributes.put(new BasicAttribute(algorithmAttributeName)); attributes.put(new BasicAttribute(hashAttributeName)); attributes.put(new BasicAttribute(seedAttributeName)); attributes.put(new BasicAttribute(sequenceAttributeName)); context.modifyAttributes(distinguishedName, DirContext.REMOVE_ATTRIBUTE, attributes); } catch (NoSuchAttributeException e) { // ignore if already clear } catch (NamingException e) { throw log.ldapRealmCredentialClearingFailed(distinguishedName, e); } } }
protected List<Address> resolveSRVEntries(String dnsQuery) { List<Address> addresses = new ArrayList<>(); try { // We are parsing this kind of structure: // {srv=SRV: 10 100 8888 9089f34a.jgroups-dns-ping.myproject.svc.cluster.local.} // The frst attribute is the type of record. We are not interested in this. Next are addresses. Attributes attributes = dnsContext.getAttributes(dnsQuery, new String[] { DNSRecordType.SRV.toString() }); if (attributes != null && attributes.getAll().hasMoreElements()) { NamingEnumeration<?> namingEnumeration = attributes.get(DNSRecordType.SRV.toString()).getAll(); while (namingEnumeration.hasMoreElements()) { try { String srvEntry = namingEnumeration.nextElement().toString(); Matcher matcher = SRV_REGEXP.matcher(srvEntry); if (matcher.find()) { String srcPort = matcher.group(1); String srcDNSRecord = matcher.group(2); // The implementation here is not optimal but it's easy to read. SRV discovery will be performed // extremely rarely, only when a fine grained discovery using ports is needed (ie: when using containers). addresses.addAll(resolveAEntries(srcDNSRecord, srcPort)); } } catch (Exception e) { log.trace("non critical DNS resolution error", e); } } } } catch (NamingException ex) { log.trace("no DNS records for query %s, ex: %s", dnsQuery, ex.getMessage()); } return addresses; }
SearchControls controls = new SearchControls(); controls.setSearchScope(SUBTREE_SCOPE); NamingEnumeration<SearchResult> renum = context.search(toDC(domainName), "(& (userPrincipalName=" + principalName + ")(objectClass=user))", controls); if (!renum.hasMore()) { System.out.println("Cannot locate user information for " + username); System.exit(1); SearchResult result = renum.next(); Attribute memberOf = result.getAttributes().get("memberOf"); if (memberOf != null) {// null if this user belongs to no group at all for (int i = 0; i < memberOf.size(); i++) { Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[] { "CN" }); Attribute att = atts.get("CN"); groups.add(new GrantedAuthorityImpl(att.get().toString()));
/** * Look into A-record at a specific DNS address. * * @return resolved IP addresses or null if no A-record was present */ @Nullable public static List<String> resolveARecord(String rootDomainName) { if (isLocalOrIp(rootDomainName)) { return null; } try { Attributes attrs = getDirContext().getAttributes(rootDomainName, new String[]{A_RECORD_TYPE, CNAME_RECORD_TYPE}); Attribute aRecord = attrs.get(A_RECORD_TYPE); Attribute cRecord = attrs.get(CNAME_RECORD_TYPE); if (aRecord != null && cRecord == null) { List<String> result = new ArrayList<>(); NamingEnumeration<String> entries = (NamingEnumeration<String>) aRecord.getAll(); while (entries.hasMore()) { result.add(entries.next()); } return result; } } catch (Exception e) { logger.warn("Cannot load A-record for eureka server address {}", rootDomainName, e); return null; } return null; }
SearchControls constraints = new SearchControls(); if (subTreeSearch) { constraints.setSearchScope (SearchControls.SUBTREE_SCOPE); constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE); constraints.setReturningAttributes(new String[] { usernameField }); NamingEnumeration answer = ctx.search("", princSearchFilter, new String[] {LdapManager.sanitizeSearchFilter(principal)}, constraints); Log.debug("LdapAuthorizationMapping: ... search finished"); if (answer == null || !answer.hasMoreElements()) { Log.debug("LdapAuthorizationMapping: Username based on principal '" + principal + "' not found."); return principal; Attributes atrs = ((SearchResult)answer.next()).getAttributes(); Attribute usernameAttribute = atrs.get(usernameField); username = (String) usernameAttribute.get(); try { if (ctx != null) { ctx.close();
SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); controls.setCountLimit(0); controls.setReturningAttributes(getAttributes()); NamingEnumeration<SearchResult> results = context.search(getSearchBase(), getSearchFilter(), controls); if (results != null && results.hasMore()) { SearchResult result = results.next(); NamingEnumeration<? extends Attribute> attribs = result.getAttributes().getAll(); while(attribs.hasMore()) { Attribute attrib = attribs.nextElement(); LDAPAttribute attribute = new LDAPAttribute(attrib.getID()); NamingEnumeration<?> vals = attrib.getAll(); while(vals.hasMore()) { Object val = vals.nextElement();
@Override public Object mapFromAttributes(final Attributes attributes) throws NamingException { final int attributeCount = attributes.size(); final Map<String, Object> mapOfAttrValues = this.createAttributeMap(attributeCount); for (final NamingEnumeration<? extends Attribute> attributesEnum = attributes.getAll(); attributesEnum.hasMore(); ) { final Attribute attribute = attributesEnum.next(); if (!this.ignoreNull || attribute.size() > 0) { final String attrName = attribute.getID(); final String key = this.getAttributeKey(attrName); final NamingEnumeration<?> valuesEnum = attribute.getAll(); final List<?> values = this.getAttributeValues(valuesEnum); mapOfAttrValues.put(key, values); } } return mapOfAttrValues; }
NamingEnumeration<SearchResult> results = c.search(userbaseDN, userSearchFilter, new Object[]{user}, SEARCH_CONTROLS); if (!results.hasMoreElements()) { if (LOG.isDebugEnabled()) { LOG.debug("doGetGroups(" + user + ") returned no groups because the " + SearchResult result = results.nextElement(); Attribute groupDNAttr = result.getAttributes().get(memberOfAttr); if (groupDNAttr == null) { throw new NamingException("The user object does not have '" + memberOfAttr + "' attribute." + "Returned user object: " + result.toString()); NamingEnumeration groupEnumeration = groupDNAttr.getAll(); while (groupEnumeration.hasMore()) { String groupDN = groupEnumeration.next().toString(); groups.add(getRelativeDistinguishedName(groupDN));
private String lookupPtrRecord(String reversedDomain) throws Exception { Attributes attrs = ctx.getAttributes(reversedDomain, new String[] {"PTR"}); for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements(); ) { Attribute attr = (Attribute) ae.next(); for (Enumeration<?> vals = attr.getAll(); vals.hasMoreElements(); ) return vals.nextElement().toString(); } return null; }
/** * convert search result into URI * * @param result * search result to convert to URI */ protected URI toURI(SearchResult result) throws Exception { Attributes attributes = result.getAttributes(); String address = (String) attributes.get("iphostnumber").get(); String port = (String) attributes.get("ipserviceport").get(); String protocol = (String) attributes.get("ipserviceprotocol").get(); URI connectorURI = new URI("static:(" + protocol + "://" + address + ":" + port + ")"); LOG.debug("retrieved URI from SearchResult [{}]", connectorURI); return connectorURI; }
private List<Map<String, Object>> search(String base, String filter) { try { SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setDerefLinkFlag(false); NamingEnumeration results = getBaseContext().search(base, filter, sc); List<Map<String, Object>> result = new ArrayList<>(); while (results.hasMore()) { Map<String, Object> item = new HashMap<>(); result.add(item); SearchResult oneRes = (SearchResult) results.next(); NamingEnumeration<? extends Attribute> fields = (oneRes.getAttributes().getAll()); for (Attribute a = fields.next(); fields.hasMore(); a = fields.next()) { item.put(a.getID(), a.get()); } } return result; } catch (Exception e) { throw new RuntimeException("Search failed: searchBase=" + base + " filter=" + filter, e); } }
}; ctx = manager.getContext(manager.getUsersBaseDN(username)); Attributes attrs = ctx.getAttributes(userDN, attributes); String name = null; Attribute nameField = attrs.get(manager.getNameField()); if (nameField != null) { name = (String)nameField.get(); Attribute emailField = attrs.get(manager.getEmailField()); if (emailField != null) { email = (String)emailField.get(); Attribute creationDateField = attrs.get("createTimestamp"); if (creationDateField != null && "".equals(((String) creationDateField.get()).trim())) { creationDate = parseLDAPDate((String) creationDateField.get()); Attribute modificationDateField = attrs.get("modifyTimestamp"); if (modificationDateField != null && "".equals(((String) modificationDateField.get()).trim())) { modificationDate = parseLDAPDate((String)modificationDateField.get()); Attribute authPassword = attrs.get("authPassword"); User user = new User(username, name, email, creationDate, modificationDate); if (authPassword != null) { try { if (ctx != null) { ctx.close();
@Override public Enumeration<String> engineAliases() { DirContext context = obtainDirContext(); if (context == null) { log.trace("Unable to obtain DirContext"); return null; } try { NamingEnumeration<SearchResult> results = context.search(searchPath, filterIterate, null, createSearchControl(new String[]{aliasAttribute})); // TODO pagination List<String> aliases = new LinkedList<>(); while (results.hasMore()) { Attribute attribute = results.next().getAttributes().get(aliasAttribute); if (attribute != null) aliases.add((String) attribute.get()); } return Collections.enumeration(aliases); } catch (NamingException e) { throw log.ldapKeyStoreFailedToIterateAliases(e); } finally { returnDirContext(context); } }
@Override public boolean process(SearchResult record) throws NamingException { result.add(record.getNameInNamespace()); NamingEnumeration<? extends Attribute> allAttributes = record.getAttributes().getAll(); while(allAttributes.hasMore()) { Attribute attribute = allAttributes.next(); addAllAttributeValuesToResult(attribute.getAll()); } return true; }
Attribute memberAttribute = result.getAttributes().get(permissionGroupMemberAttribute); NamingEnumeration<?> memberAttributeEnum = memberAttribute.getAll(); while (memberAttributeEnum.hasMoreElements()) { String memberDn = (String) memberAttributeEnum.nextElement(); boolean group = false; boolean user = false; Attribute memberEntryObjectClassAttribute = memberAttributes.get("objectClass"); NamingEnumeration<?> memberEntryObjectClassAttributeEnum = memberEntryObjectClassAttribute.getAll(); while (memberEntryObjectClassAttributeEnum.hasMoreElements()) { String objectClass = (String) memberEntryObjectClassAttributeEnum.nextElement(); Attribute name = memberAttributes.get(groupNameAttribute); if (name == null) { LOG.error("Policy not applied! Group {} does not have name attribute {} under entry {}", new Object[]{ memberDn, groupNameAttribute, result.getNameInNamespace() }); break; principalName = (String) name.get(); Attribute name = memberAttributes.get(userNameAttribute); if (name == null) { LOG.error("Policy not applied! User {} does not have name attribute {} under entry {}", new Object[]{ memberDn, userNameAttribute, result.getNameInNamespace() });
private Set<String> getGroupMembershipsIntersectingWithRestrictedGroups(AutoclosingLdapContext context, String userName) throws NamingException { userName = userNameBaseOnGroupClass(userName); final String filter = String.format("(&(%s=%s)(objectClass=%s))", configuration.getGroupMembershipAttribute(), userName, configuration.getGroupClassName()); final NamingEnumeration<SearchResult> result = context.search(configuration.getGroupFilter(), filter, new SearchControls()); ImmutableSet.Builder<String> overlappingGroups = ImmutableSet.builder(); try { while (result.hasMore()) { SearchResult next = result.next(); if (next.getAttributes() != null && next.getAttributes().get(configuration.getGroupNameAttribute()) != null) { String group = (String) next.getAttributes().get(configuration.getGroupNameAttribute()).get(0); if (configuration.getRestrictToGroups().isEmpty() || configuration.getRestrictToGroups().contains(group)) { overlappingGroups.add(group); } } } return overlappingGroups.build(); } finally { result.close(); } }
public static int get_OLD_Gid(LDAPConfiguration cfg2, String groupName) throws Throwable { LDAPConfiguration cfg = cfg2.clone(); cfg.setSearchBase("ou=Groups,dc=ncsa,dc=illinois,dc=edu"); LDAPClaimsSource claimsSource = new LDAPClaimsSource(cfg, null); DirContext dirContext = new InitialDirContext(claimsSource.createEnv(cfg)); LdapContext ctx = (LdapContext) dirContext.lookup(cfg.getSearchBase()); SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(new String[]{"gidNumber"}); String filter = "(&(cn=" + groupName + "))"; NamingEnumeration e = ctx.search(cfg.getContextName(), filter, ctls); while (e.hasMoreElements()) { SearchResult entry = (SearchResult) e.next(); Attributes a = entry.getAttributes(); Attribute attribute = a.get("gidNumber"); if (attribute == null) { continue; } String xxx = String.valueOf(attribute.get(0)); if (xxx != null && !xxx.isEmpty()) { ctx.close(); return Integer.parseInt(xxx); } } return -1; }
public Object mapFromContext(Object ctx) { DirContextAdapter adapter = (DirContextAdapter) ctx; Map<String, List<String>> record = new HashMap<String, List<String>>(); if (attributeNames == null || attributeNames.length == 0) { try { for (NamingEnumeration ae = adapter.getAttributes().getAll(); ae .hasMore();) { Attribute attr = (Attribute) ae.next(); extractStringAttributeValues(adapter, record, attr.getID()); } } catch (NamingException x) { org.springframework.ldap.support.LdapUtils .convertLdapException(x); } } else { for (String attributeName : attributeNames) { extractStringAttributeValues(adapter, record, attributeName); } } record.put(DN_KEY, Arrays.asList(getAdapterDN(adapter))); set.add(record); return null; } };