List of usage examples for javax.naming.directory Attribute getID
String getID();
From source file:org.apache.zeppelin.realm.ActiveDirectoryGroupRealm.java
private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException { Set<String> roleNames = new LinkedHashSet<>(); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String userPrincipalName = username; if (this.principalSuffix != null && userPrincipalName.indexOf('@') < 0) { userPrincipalName += principalSuffix; }/*from w w w .j av a2 s . c om*/ String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))"; Object[] searchArguments = new Object[] { userPrincipalName }; NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); if (log.isDebugEnabled()) { log.debug("Retrieving group names for user [" + sr.getName() + "]"); } Attributes attrs = sr.getAttributes(); if (attrs != null) { NamingEnumeration ae = attrs.getAll(); while (ae.hasMore()) { Attribute attr = (Attribute) ae.next(); if (attr.getID().equals("memberOf")) { Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr); if (log.isDebugEnabled()) { log.debug("Groups found for user [" + username + "]: " + groupNames); } Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames); roleNames.addAll(rolesForGroups); } } } } return roleNames; }
From source file:org.apache.zeppelin.server.ActiveDirectoryGroupRealm.java
private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException { Set<String> roleNames = new LinkedHashSet<>(); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String userPrincipalName = username; if (principalSuffix != null) { userPrincipalName += principalSuffix; }//from w w w . ja v a2 s. co m String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))"; Object[] searchArguments = new Object[] { userPrincipalName }; NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); if (log.isDebugEnabled()) { log.debug("Retrieving group names for user [" + sr.getName() + "]"); } Attributes attrs = sr.getAttributes(); if (attrs != null) { NamingEnumeration ae = attrs.getAll(); while (ae.hasMore()) { Attribute attr = (Attribute) ae.next(); if (attr.getID().equals("memberOf")) { Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr); if (log.isDebugEnabled()) { log.debug("Groups found for user [" + username + "]: " + groupNames); } Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames); roleNames.addAll(rolesForGroups); } } } } return roleNames; }
From source file:LDAPTest.java
/** * Saves the changes that the user made. *///w ww . j a v a 2 s . c o m public void saveEntry() { try { if (dataPanel == null) return; if (context == null) context = getContext(); if (uidField.getText().equals(uid)) // update existing entry { String dn = "uid=" + uidField.getText() + ",ou=people,dc=mycompany,dc=com"; Attributes editedAttrs = dataPanel.getEditedAttributes(); NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll(); while (attrEnum.hasMore()) { Attribute attr = attrEnum.next(); String id = attr.getID(); Attribute editedAttr = editedAttrs.get(id); if (editedAttr != null && !attr.get().equals(editedAttr.get())) context.modifyAttributes(dn, DirContext.REPLACE_ATTRIBUTE, new BasicAttributes(id, editedAttr.get())); } } else // create new entry { String dn = "uid=" + uidField.getText() + ",ou=people,dc=mycompany,dc=com"; attrs = dataPanel.getEditedAttributes(); Attribute objclass = new BasicAttribute("objectClass"); objclass.add("uidObject"); objclass.add("person"); attrs.put(objclass); attrs.put("uid", uidField.getText()); context.createSubcontext(dn, attrs); } findEntry(); } catch (NamingException e) { JOptionPane.showMessageDialog(LDAPFrame.this, e); e.printStackTrace(); } catch (IOException e) { JOptionPane.showMessageDialog(LDAPFrame.this, e); e.printStackTrace(); } }
From source file:org.apache.cxf.sts.claims.LdapClaimsHandler.java
public ProcessedClaimCollection retrieveClaimValues(ClaimCollection claims, ClaimsParameters parameters) { String user = null;//from w ww. ja v a 2 s . c o m boolean useLdapLookup = false; Principal principal = parameters.getPrincipal(); if (principal instanceof KerberosPrincipal) { KerberosPrincipal kp = (KerberosPrincipal) principal; StringTokenizer st = new StringTokenizer(kp.getName(), "@"); user = st.nextToken(); } else if (principal instanceof X500Principal) { X500Principal x500p = (X500Principal) principal; LOG.warning("Unsupported principal type X500: " + x500p.getName()); return new ProcessedClaimCollection(); } else if (principal != null) { user = principal.getName(); if (user == null) { LOG.warning("User must not be null"); return new ProcessedClaimCollection(); } useLdapLookup = LdapUtils.isDN(user); } else { LOG.warning("Principal is null"); return new ProcessedClaimCollection(); } if (LOG.isLoggable(Level.FINEST)) { LOG.finest("Retrieve claims for user " + user); } Map<String, Attribute> ldapAttributes = null; if (useLdapLookup) { AttributesMapper mapper = new AttributesMapper() { public Object mapFromAttributes(Attributes attrs) throws NamingException { Map<String, Attribute> map = new HashMap<String, Attribute>(); NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll(); while (attrEnum.hasMore()) { Attribute att = attrEnum.next(); map.put(att.getID(), att); } return map; } }; Object result = ldap.lookup(user, mapper); ldapAttributes = CastUtils.cast((Map<?, ?>) result); } else { List<String> searchAttributeList = new ArrayList<String>(); for (Claim claim : claims) { if (getClaimsLdapAttributeMapping().keySet().contains(claim.getClaimType().toString())) { searchAttributeList.add(getClaimsLdapAttributeMapping().get(claim.getClaimType().toString())); } else { if (LOG.isLoggable(Level.FINER)) { LOG.finer("Unsupported claim: " + claim.getClaimType()); } } } String[] searchAttributes = null; searchAttributes = searchAttributeList.toArray(new String[searchAttributeList.size()]); ldapAttributes = LdapUtils.getAttributesOfEntry(ldap, this.userBaseDn, this.getObjectClass(), this.getUserNameAttribute(), user, searchAttributes); } if (ldapAttributes == null || ldapAttributes.size() == 0) { //No result if (LOG.isLoggable(Level.INFO)) { LOG.finest("User '" + user + "' not found"); } return new ProcessedClaimCollection(); } ProcessedClaimCollection claimsColl = new ProcessedClaimCollection(); for (Claim claim : claims) { URI claimType = claim.getClaimType(); String ldapAttribute = getClaimsLdapAttributeMapping().get(claimType.toString()); Attribute attr = ldapAttributes.get(ldapAttribute); if (attr == null) { if (LOG.isLoggable(Level.FINEST)) { LOG.finest("Claim '" + claim.getClaimType() + "' is null"); } } else { ProcessedClaim c = new ProcessedClaim(); c.setClaimType(claimType); c.setPrincipal(principal); StringBuilder claimValue = new StringBuilder(); try { NamingEnumeration<?> list = (NamingEnumeration<?>) attr.getAll(); while (list.hasMore()) { Object obj = list.next(); if (!(obj instanceof String)) { LOG.warning("LDAP attribute '" + ldapAttribute + "' has got an unsupported value type"); break; } String itemValue = (String) obj; if (this.isX500FilterEnabled()) { try { X500Principal x500p = new X500Principal(itemValue); itemValue = x500p.getName(); int index = itemValue.indexOf('='); itemValue = itemValue.substring(index + 1, itemValue.indexOf(',', index)); } catch (Exception ex) { //Ignore, not X500 compliant thus use the whole string as the value } } claimValue.append(itemValue); if (list.hasMore()) { claimValue.append(this.getDelimiter()); } } } catch (NamingException ex) { LOG.warning("Failed to read value of LDAP attribute '" + ldapAttribute + "'"); } c.addValue(claimValue.toString()); // c.setIssuer(issuer); // c.setOriginalIssuer(originalIssuer); // c.setNamespace(namespace); claimsColl.add(c); } } return claimsColl; }
From source file:org.springframework.ldap.ldif.parser.LdifParser.java
private void addAttributeToRecord(String buffer, LdapAttributes record) { try {//from w w w . ja v a 2s . com if (StringUtils.isNotEmpty(buffer) && record != null) { //Validate previous attribute and add to record. Attribute attribute = attributePolicy.parse(buffer); if (attribute.getID().equalsIgnoreCase("dn")) { log.trace("...adding DN to record."); String dn; if (attribute.get() instanceof byte[]) { dn = new String((byte[]) attribute.get()); } else { dn = (String) attribute.get(); } record.setDN(new DistinguishedName(dn)); } else { log.trace("...adding attribute to record."); Attribute attr = record.get(attribute.getID()); if (attr != null) { attr.add(attribute.get()); } else { record.put(attribute); } } } } catch (NamingException e) { log.error(e); } catch (NoSuchElementException e) { log.error(e); } }
From source file:com.springsource.insight.plugin.ldap.TestLdapContext.java
private void logAttributes(String location, Attributes attrs) throws NamingException { NamingEnumeration<? extends Attribute> values = attrs.getAll(); try {/* w w w.j ava 2s . co m*/ while ((values != null) && values.hasMore()) { Attribute aValue = values.next(); String id = aValue.getID(); Collection<?> valsList = Collections.list(aValue.getAll()); logger.trace(location + "[" + id + "]: " + valsList); } } finally { values.close(); } }
From source file:org.fao.geonet.kernel.security.ldap.LdapUserDetailsManager.java
public void updateUser(UserDetails user) { DistinguishedName dn = usernameMapper.buildDn(user.getUsername()); logger.debug("Updating user '" + user.getUsername() + "' with DN '" + dn + "'"); List<GrantedAuthority> authorities = getUserAuthorities(dn, user.getUsername()); DirContextAdapter ctx = loadUserAsContext(dn, user.getUsername()); ctx.setUpdateMode(true);/*from w w w. java2s . com*/ copyToContext(user, ctx); // Remove the objectclass attribute from the list of mods (if present). List<ModificationItem> mods = new LinkedList<ModificationItem>(Arrays.asList(ctx.getModificationItems())); ListIterator<ModificationItem> modIt = mods.listIterator(); while (modIt.hasNext()) { ModificationItem mod = (ModificationItem) modIt.next(); Attribute a = mod.getAttribute(); if ("objectclass".equalsIgnoreCase(a.getID())) { modIt.remove(); } } template.modifyAttributes(dn, mods.toArray(new ModificationItem[mods.size()])); // template.rebind(dn, ctx, null); // Remove the old authorities and replace them with the new one removeAuthorities(dn, authorities); addAuthorities(dn, user.getAuthorities()); }
From source file:org.apache.geode.internal.net.SocketCreator.java
/** * This method uses JNDI to look up an address in DNS and return its name * /*from w w w . j av a 2s.c o m*/ * @param addr * * @return the host name associated with the address or null if lookup isn't possible or there is * no host name for this address */ public static String reverseDNS(InetAddress addr) { byte[] addrBytes = addr.getAddress(); // reverse the address suitable for reverse lookup String lookup = ""; for (int index = addrBytes.length - 1; index >= 0; index--) { lookup = lookup + (addrBytes[index] & 0xff) + '.'; } lookup += "in-addr.arpa"; // System.out.println("Looking up: " + lookup); try { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory"); DirContext ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(lookup, new String[] { "PTR" }); for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements();) { Attribute attr = (Attribute) ae.next(); for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) { Object elem = vals.nextElement(); if ("PTR".equals(attr.getID()) && elem != null) { return elem.toString(); } } } ctx.close(); } catch (Exception e) { // ignored } return null; }
From source file:org.springframework.security.ldap.SpringSecurityLdapTemplate.java
/** * Performs a search using the supplied filter and returns the values of each named * attribute found in all entries matched by the search. Note that one directory entry * may have several values for the attribute. Intended for role searches and similar * scenarios.//from w w w . j a va2 s. c o m * * @param base the DN to search in * @param filter search filter to use * @param params the parameters to substitute in the search filter * @param attributeNames the attributes' values that are to be retrieved. * * @return the set of String values for each attribute found in all the matching * entries. The attribute name is the key for each set of values. In addition each map * contains the DN as a String with the key predefined key {@link #DN_KEY}. */ public Set<Map<String, List<String>>> searchForMultipleAttributeValues(final String base, final String filter, final Object[] params, final String[] attributeNames) { // Escape the params acording to RFC2254 Object[] encodedParams = new String[params.length]; for (int i = 0; i < params.length; i++) { encodedParams[i] = LdapEncoder.filterEncode(params[i].toString()); } String formattedFilter = MessageFormat.format(filter, encodedParams); logger.debug("Using filter: " + formattedFilter); final HashSet<Map<String, List<String>>> set = new HashSet<Map<String, List<String>>>(); ContextMapper roleMapper = new ContextMapper() { 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; } }; SearchControls ctls = new SearchControls(); ctls.setSearchScope(searchControls.getSearchScope()); ctls.setReturningAttributes(attributeNames != null && attributeNames.length > 0 ? attributeNames : null); search(base, formattedFilter, ctls, roleMapper); return set; }
From source file:org.springframework.ldap.core.LdapAttributes.java
/** * Returns a string representation of the object in LDIF format. * //from w w w . j a v a 2 s . co m * @return {@link java.lang.String} formated to RFC2849 LDIF specifications. */ public String toString() { StringBuilder sb = new StringBuilder(); try { DistinguishedName dn = getDN(); if (!dn.toString().matches(SAFE_INIT_CHAR + SAFE_CHAR + "*")) { sb.append("dn:: " + new BASE64Encoder().encode(dn.toString().getBytes()) + "\n"); } else { sb.append("dn: " + getDN() + "\n"); } NamingEnumeration<Attribute> attributes = getAll(); while (attributes.hasMore()) { Attribute attribute = attributes.next(); NamingEnumeration<?> values = attribute.getAll(); while (values.hasMore()) { Object value = values.next(); if (value instanceof String) sb.append(attribute.getID() + ": " + (String) value + "\n"); else if (value instanceof byte[]) sb.append(attribute.getID() + ":: " + new BASE64Encoder().encode((byte[]) value) + "\n"); else if (value instanceof URI) sb.append(attribute.getID() + ":< " + (URI) value + "\n"); else { sb.append(attribute.getID() + ": " + value + "\n"); } } } } catch (NamingException e) { log.error("Error formating attributes for output.", e); sb = new StringBuilder(); } return sb.toString(); }