List of usage examples for javax.naming.directory Attributes get
Attribute get(String attrID);
From source file:de.fiz.ddb.aas.utils.LDAPEngineUtility.java
/** * get attribute values of given resource and attributes. * //from w w w .j a v a 2 s . co m * @param scope * scope * @param id * id of resource * @param attributeName * attribute-name to retrieve * * @return String attribute value * @throws NamingException * @throws IllegalAccessException */ public Map<String, String> getResourceAttributes(Scope scope, String id, String[] attributeNames) throws NamingException, IllegalAccessException { Map<String, String> returnMap = new HashMap<String, String>(); String baseDn = null; String filter = getIdFilter(scope, id); int levelScope = 0; InitialLdapContext ctx = null; NamingEnumeration<SearchResult> results = null; if (scope == Scope.ORGANIZATION) { baseDn = LDAPConnector.getSingletonInstance().getInstitutionBaseDN(); levelScope = SearchControls.SUBTREE_SCOPE; } else if (scope == Scope.PERSON) { baseDn = LDAPConnector.getSingletonInstance().getPersonBaseDN(); levelScope = SearchControls.ONELEVEL_SCOPE; } try { ctx = LDAPConnector.getSingletonInstance().takeCtx(); results = query(ctx, baseDn, filter, attributeNames, levelScope); if (results.hasMore()) { SearchResult searchResult = results.next(); if (results.hasMore()) { throw new IllegalAccessException("found more than one object with id=" + id); } Attributes attributes = searchResult.getAttributes(); for (int i = 0; i < attributeNames.length; i++) { Attribute attribute = attributes.get(attributeNames[i]); if (attribute == null) { returnMap.put(attributeNames[i], (String) null); } else { returnMap.put(attributeNames[i], (String) attribute.get()); } } return returnMap; } else { throw new NameNotFoundException("id not found"); } } finally { if (ctx != null) { try { LDAPConnector.getSingletonInstance().putCtx(ctx); } catch (IllegalAccessException ex) { LOG.log(Level.SEVERE, null, ex); } } if (results != null) { try { results.close(); } catch (NamingException e) { LOG.log(Level.WARNING, null, e); } } } }
From source file:com.wfp.utils.LDAPUtils.java
public static String getUserImageAsString(String uid) { String base64String = null; if (uid != null && uid != "") { // Specify the attributes to return String searchFilter = "(&" + FILTER_LDAP_USERS + "((uid=" + uid + ")))"; String searchBase = LDAP_FILTER_URL + "uid=" + uid + "," + LDAP_BASE; String returnedAtts[] = { "" + PROPERTY_IMAGE }; // Specify the search scope SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setReturningAttributes(returnedAtts); // Search for objects using the filter try {//from www . j ava 2 s . c o m NamingEnumeration results = getSearchResults(getLDAPContext(), searchCtls, searchFilter, searchBase); while (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); Attribute attr = attributes.get(PROPERTY_IMAGE); if (attr != null) base64String = new String( org.apache.commons.codec.binary.Base64.encodeBase64((byte[]) attr.get())); } } catch (NamingException e) { Logger.error(" Error occured while fetching user image 1334: getUserImageBytes(String uid):[" + e.getLocalizedMessage() + "]", LDAPUtils.class); } } return base64String; }
From source file:eu.europa.esig.dss.client.http.commons.CommonsDataLoader.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 * - ex URL from AIA ldap://xadessrv.plugtests.net/CN=LevelBCAOK,OU=Plugtests_2015-2016,O=ETSI,C=FR?cACertificate;binary * * @param urlString//from w w w . j a va 2s . c o m * @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 { String attributeName = StringUtils.substringAfterLast(urlString, "?"); if (StringUtils.isEmpty(attributeName)) { // default was CRL attributeName = "certificateRevocationList;binary"; } final DirContext ctx = new InitialDirContext(env); final Attributes attributes = ctx.getAttributes(StringUtils.EMPTY); final Attribute attribute = attributes.get(attributeName); final byte[] ldapBytes = (byte[]) attribute.get(); if (ArrayUtils.isEmpty(ldapBytes)) { throw new DSSException("Cannot download CRL from: " + urlString); } return ldapBytes; } catch (Exception e) { LOG.warn(e.getMessage(), e); } return null; }
From source file:com.evolveum.midpoint.model.common.expression.functions.BasicExpressionFunctions.java
public String determineLdapSingleAttributeValue(String dn, String attributeName, Collection<?> values) throws NamingException { if (values == null || values.isEmpty()) { return null; }//from ww w . j ava 2s .c o m Collection<String> stringValues = null; // Determine item type, try to convert to strings Object firstElement = values.iterator().next(); if (firstElement instanceof String) { stringValues = (Collection) values; } else if (firstElement instanceof Element) { stringValues = new ArrayList<String>(values.size()); for (Object value : values) { Element element = (Element) value; stringValues.add(element.getTextContent()); } } else { throw new IllegalArgumentException("Unexpected value type " + firstElement.getClass()); } if (stringValues.size() == 1) { return stringValues.iterator().next(); } if (StringUtils.isBlank(dn)) { throw new IllegalArgumentException( "No dn argument specified, cannot determine which of " + values.size() + " values to use"); } LdapName parsedDn = new LdapName(dn); for (int i = 0; i < parsedDn.size(); i++) { Rdn rdn = parsedDn.getRdn(i); Attributes rdnAttributes = rdn.toAttributes(); NamingEnumeration<String> rdnIDs = rdnAttributes.getIDs(); while (rdnIDs.hasMore()) { String rdnID = rdnIDs.next(); Attribute attribute = rdnAttributes.get(rdnID); if (attributeName.equals(attribute.getID())) { for (int j = 0; j < attribute.size(); j++) { Object value = attribute.get(j); if (stringValues.contains(value)) { return (String) value; } } } } } // Fallback. No values in DN. Just return the first alphabetically-wise value. return Collections.min(stringValues); }
From source file:com.adito.activedirectory.ActiveDirectoryUserDatabase.java
private Collection<ActiveDirectoryGroup> getUsersGroups(Attributes attributes) throws NamingException { Attribute memberOfAttribute = attributes.get(MEMBER_OF_ATTIBUTE); if (memberOfAttribute == null) { return Collections.<ActiveDirectoryGroup>emptyList(); }// w ww .ja v a 2s. c o m Collection<ActiveDirectoryGroup> groups = new ArrayList<ActiveDirectoryGroup>(); for (int index = 0; index < memberOfAttribute.size(); index++) { String groupDn = (String) memberOfAttribute.get(index); groups.addAll(getGroupsByDn(groupDn)); } return groups; }
From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java
/** * Performs recursive group membership lookup. * * This was how we did the lookup traditionally until we discovered 1.2.840.113556.1.4.1941. * But various people reported that it slows down the execution tremendously to the point that it is unusable, * while others seem to report that it runs faster than recursive search (http://social.technet.microsoft.com/Forums/fr-FR/f238d2b0-a1d7-48e8-8a60-542e7ccfa2e8/recursive-retrieval-of-all-ad-group-memberships-of-a-user?forum=ITCG) * * This implementation is kept for Windows 2003 that doesn't support 1.2.840.113556.1.4.1941, but it can be also * enabled for those who are seeing the performance problem. * * See JENKINS-22830// ww w .ja v a 2 s . c om */ private void recursiveGroupLookup(DirContext context, Attributes id, Set<GrantedAuthority> groups) throws NamingException { Stack<Attributes> q = new Stack<Attributes>(); q.push(id); while (!q.isEmpty()) { Attributes identity = q.pop(); LOGGER.finer("Looking up group of " + identity); Attribute memberOf = identity.get("memberOf"); if (memberOf == null) continue; for (int i = 0; i < memberOf.size(); i++) { try { LOGGER.log(Level.FINE, "Trying to get the CN of {0}", memberOf.get(i)); Attributes group = context.getAttributes(new LdapName(memberOf.get(i).toString()), new String[] { "CN", "memberOf" }); Attribute cn = group.get("CN"); if (cn == null) { LOGGER.fine("Failed to obtain CN of " + memberOf.get(i)); continue; } if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine(cn.get() + " is a member of " + memberOf.get(i)); if (groups.add(new GrantedAuthorityImpl(cn.get().toString()))) { q.add(group); // recursively look for groups that this group is a member of. } } catch (NameNotFoundException e) { LOGGER.fine("Failed to obtain CN of " + memberOf.get(i)); } } } }
From source file:org.jenkinsci.plugins.reverse_proxy_auth.ReverseProxySecurityRealm.java
/** * Infer the root DN.//w w w . j a v a 2s.c o m * * @return null if not found. */ private String inferRootDN(String server) { try { Hashtable<String, String> props = new Hashtable<String, String>(); if (managerDN != null) { props.put(Context.SECURITY_PRINCIPAL, managerDN); props.put(Context.SECURITY_CREDENTIALS, getManagerPassword()); } props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, toProviderUrl(fixNull(getServerUrl()), "")); DirContext ctx = new InitialDirContext(props); Attributes atts = ctx.getAttributes(""); Attribute a = atts.get("defaultNamingContext"); if (a != null && a.get() != null) { // this entry is available on Active Directory. See http://msdn2.microsoft.com/en-us/library/ms684291(VS.85).aspx return a.get().toString(); } a = atts.get("namingcontexts"); if (a == null) { LOGGER.warning("namingcontexts attribute not found in root DSE of " + server); return null; } return a.get().toString(); } catch (NamingException e) { LOGGER.log(Level.WARNING, "Failed to connect to LDAP to infer Root DN for " + server, e); return null; } }
From source file:org.jasig.cas.adaptors.ldap.LdapPasswordPolicyEnforcer.java
/** * Retrieves the password policy results from the configured ldap repository based on the attributes defined. * @param userId authenticating user id//from w w w. j a va2 s . com * @return {@code null} if the user id cannot be found, or the {@code LdapPasswordPolicyResult} instance. */ private LdapPasswordPolicyResult getResultsFromLdap(final String userId) { String[] attributeIds; final List<String> attributeList = new ArrayList<String>(); attributeList.add(this.dateAttribute); if (this.warningDaysAttribute != null) { attributeList.add(this.warningDaysAttribute); } if (this.validDaysAttribute != null) { attributeList.add(this.validDaysAttribute); } if (this.noWarnAttribute != null) { attributeList.add(this.noWarnAttribute); } attributeIds = new String[attributeList.size()]; attributeList.toArray(attributeIds); final String searchFilter = LdapUtils.getFilterWithValues(this.filter, userId); logger.debug("Starting search with searchFilter: {}", searchFilter); String attributeListLog = attributeIds[0]; for (int i = 1; i < attributeIds.length; i++) { attributeListLog = attributeListLog.concat(":" + attributeIds[i]); } logger.debug("Returning attributes {}", attributeListLog); try { final AttributesMapper mapper = new AttributesMapper() { @Override public Object mapFromAttributes(final Attributes attrs) throws NamingException { final LdapPasswordPolicyResult result = new LdapPasswordPolicyResult(userId); if (LdapPasswordPolicyEnforcer.this.dateAttribute != null) { if (attrs.get(LdapPasswordPolicyEnforcer.this.dateAttribute) != null) { final String date = (String) attrs.get(LdapPasswordPolicyEnforcer.this.dateAttribute) .get(); result.setDateResult(date); } } if (LdapPasswordPolicyEnforcer.this.warningDaysAttribute != null) { if (attrs.get(LdapPasswordPolicyEnforcer.this.warningDaysAttribute) != null) { final String warn = (String) attrs .get(LdapPasswordPolicyEnforcer.this.warningDaysAttribute).get(); result.setWarnDaysResult(warn); } } if (LdapPasswordPolicyEnforcer.this.noWarnAttribute != null) { if (attrs.get(LdapPasswordPolicyEnforcer.this.noWarnAttribute) != null) { final String attrib = (String) attrs .get(LdapPasswordPolicyEnforcer.this.noWarnAttribute).get(); result.setNoWarnAttributeResult(attrib); } } if (attrs.get(LdapPasswordPolicyEnforcer.this.validDaysAttribute) != null) { final String valid = (String) attrs.get(LdapPasswordPolicyEnforcer.this.validDaysAttribute) .get(); result.setValidDaysResult(valid); } return result; } }; final List<?> resultList = this.ldapTemplate.search(this.searchBase, searchFilter, getSearchControls(attributeIds), mapper); if (resultList.size() > 0) { return (LdapPasswordPolicyResult) resultList.get(0); } } catch (final Exception e) { logger.error(e.getMessage(), e); } return null; }
From source file:com.adito.activedirectory.ActiveDirectoryUserDatabase.java
private String[] getParents(Attributes attributes) throws NamingException { List<String> parents = new ArrayList<String>(); Attribute memberOfAttribute = attributes.get(MEMBER_OF_ATTIBUTE); if (memberOfAttribute != null) { final PagedResultTemplate pagedResultTemplate = configuration.getPagedResultTemplate(); for (int index = 0; index < memberOfAttribute.size(); index++) { String parentDn = (String) memberOfAttribute.get(index); if (pagedResultTemplate.isDnValid(parentDn)) { parents.add(parentDn); // valid parent so record }/*from w w w . j ava 2s . c o m*/ } } return parents.toArray(new String[parents.size()]); }
From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java
/** * Resolves all the groups that the user is in. * * We now use <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms680275(v=vs.85).aspx">tokenGroups</a> * attribute, which is a computed attribute that lists all the SIDs of the groups that the user is directly/indirectly in. * We then use that to retrieve all the groups in one query and resolve their canonical names. * * @param userDN//from www. j av a 2 s . c o m * User's distinguished name. * @param context Used for making queries. */ private Set<GrantedAuthority> resolveGroups(String domainDN, String userDN, DirContext context) throws NamingException { if (userDN.contains("/")) { userDN = userDN.replace("/", "\\/"); } Set<GrantedAuthority> groups = new HashSet<GrantedAuthority>(); LOGGER.log(Level.FINER, "Looking up group of {0}", userDN); Attributes id = context.getAttributes(userDN, new String[] { "tokenGroups", "memberOf", "CN" }); Attribute tga = id.get("tokenGroups"); if (tga == null) { // tga will be null if you are not using a global catalogue // or if the user is not actually a member of any security groups. LOGGER.log(Level.FINE, "Failed to retrieve tokenGroups for {0}", userDN); // keep on trucking as we can still use memberOf for Distribution Groups. } else { // build up the query to retrieve all the groups StringBuilder query = new StringBuilder("(|"); List<byte[]> sids = new ArrayList<byte[]>(); NamingEnumeration<?> tokenGroups = tga.getAll(); while (tokenGroups.hasMore()) { byte[] gsid = (byte[]) tokenGroups.next(); query.append("(objectSid={" + sids.size() + "})"); sids.add(gsid); } tokenGroups.close(); query.append(")"); NamingEnumeration<SearchResult> renum = new LDAPSearchBuilder(context, domainDN).subTreeScope() .returns("cn").search(query.toString(), sids.toArray()); parseMembers(userDN, groups, renum); renum.close(); } {/* stage 2: use memberOf to find groups that aren't picked up by tokenGroups. This includes distribution groups */ LOGGER.fine("Stage 2: looking up via memberOf"); while (true) { switch (groupLookupStrategy) { case TOKENGROUPS: // no extra lookup - ever. return groups; case AUTO: // try the accurate one first, and if it's too slow fall back to recursive in the hope that it's faster long start = System.nanoTime(); boolean found = false; long duration = 0; try { found = chainGroupLookup(domainDN, userDN, context, groups); duration = TimeUnit2.NANOSECONDS.toSeconds(System.nanoTime() - start); } catch (TimeLimitExceededException e) { LOGGER.log(Level.WARNING, "The LDAP request did not terminate within the specified time limit. AD will fall back to recursive lookup", e); } catch (NamingException e) { if (e.getMessage().contains("LDAP response read timed out")) { LOGGER.log(Level.WARNING, "LDAP response read time out. AD will fall back to recursive lookup", e); } else { throw e; } } if (!found && duration >= 10) { LOGGER.log(Level.WARNING, "Group lookup via Active Directory's 'LDAP_MATCHING_RULE_IN_CHAIN' extension timed out after {0} seconds. Falling back to recursive group lookup strategy for this and future queries", duration); groupLookupStrategy = GroupLookupStrategy.RECURSIVE; continue; } else if (found && duration >= 10) { LOGGER.log(Level.WARNING, "Group lookup via Active Directory's 'LDAP_MATCHING_RULE_IN_CHAIN' extension matched user's groups but took {0} seconds to run. Switching to recursive lookup for future group lookup queries", duration); groupLookupStrategy = GroupLookupStrategy.RECURSIVE; return groups; } else if (!found) { LOGGER.log(Level.WARNING, "Group lookup via Active Directory's 'LDAP_MATCHING_RULE_IN_CHAIN' extension failed. Falling back to recursive group lookup strategy for this and future queries"); groupLookupStrategy = GroupLookupStrategy.RECURSIVE; continue; } else { // it run fast enough, so let's stick to it groupLookupStrategy = GroupLookupStrategy.CHAIN; return groups; } case RECURSIVE: recursiveGroupLookup(context, id, groups); return groups; case CHAIN: chainGroupLookup(domainDN, userDN, context, groups); return groups; } } } }