public static String[] getAttributeStringArray(Attributes attributes, String id) throws NamingException { if (Validator.isNull(id)) { return null; } Attribute attribute = attributes.get(id); if (attribute == null) { return new String[0]; } int size = attribute.size(); if (size == 0) { return null; } String[] array = new String[size]; for (int i = 0; i < size; i++) { Object object = attribute.get(i); if (object == null) { array[i] = StringPool.BLANK; } else { array[i] = object.toString(); } } return array; }
public Map<String, String> getAttributes(User user) throws DataSourceException, ConfigException { try { String s = "(&(objectClass=" + source.getUsersObjectClassValue() + ")(" + source.getUsersIdKey() + "=" + user.getUid() + "))"; List<SearchResult> r = this.search(s, SecurityEntityType.USER); if (!r.isEmpty()) { Attributes attrs = r.get(0).getAttributes(); Map<String, String> items = new HashMap<String, String>(); NamingEnumeration<? extends Attribute> lst = attrs.getAll(); while (lst.hasMoreElements()) { Attribute attr = lst.nextElement(); if (attr.get() != null) { items.put(attr.getID(), attr.get().toString()); } } return items; } else { return null; } } catch (javax.naming.AuthenticationException e) { throw new ConfigException(e, "LDAP connection failed, please check your settings"); } catch (NamingException e) { throw new DataSourceException(e, "LDAP Exception : " + e.getMessage()); } }
public static int verifyMaliciousPassword(String login, String mail) { String mailAdresse = ""; Ldap adminConnection = new Ldap(); adminConnection.SetEnv( Play.configuration.getProperty("ldap.host"), Play.configuration.getProperty("ldap.admin.dn"), Play.configuration.getProperty("ldap.admin.password")); Attributes f = adminConnection.getUserInfo(adminConnection.getLdapEnv(), login); try { NamingEnumeration e = f.getAll(); while (e.hasMore()) { javax.naming.directory.Attribute a = (javax.naming.directory.Attribute) e.next(); String attributeName = a.getID(); String attributeValue = ""; Enumeration values = a.getAll(); while (values.hasMoreElements()) { attributeValue = values.nextElement().toString(); } if (attributeName.equals("mail")) { mailAdresse = attributeValue; } } } catch (javax.naming.NamingException e) { System.out.println(e.getMessage()); return 0; } finally { if (mailAdresse.equals("")) { return Invitation.USER_NOTEXIST; } else if (mailAdresse.equals(mail)) { return Invitation.ADDRESSES_MATCHE; } else { return Invitation.ADDRESSES_NOTMATCHE; } } }
/** * @param thisA * @param that * @return boolean * @throws Throwable */ public boolean attrEquals(Attribute thisA, Attribute that) throws Throwable { int sz = thisA.size(); if (sz != that.size()) { return false; } if (sz == 0) { return true; } NamingEnumeration ne = thisA.getAll(); if (ne == null) { return false; } while (ne.hasMore()) { if (!that.contains(ne.next())) { return false; } } return true; }
/** * Returns the host name and port that the specified XMPP server can be reached at for * client-to-server communication. A DNS lookup for a SRV record in the form * "_xmpp-client._tcp.example.com" is attempted, according to section 14.4 of RFC 3920. If that * lookup fails, a lookup in the older form of "_jabber._tcp.example.com" is attempted since * servers that implement an older version of the protocol may be listed using that notation. If * that lookup fails as well, it's assumed that the XMPP server lives at the host resolved by a * DNS lookup at the specified domain on the default port of 5222. * * <p>As an example, a lookup for "example.com" may return "im.example.com:5269". * * <p>Note on SRV record selection. We now check priority and weight, but we still don't do this * correctly. The missing behavior is this: if we fail to reach a host based on its SRV record * then we need to select another host from the other SRV records. In Smack 3.1.1 we're not going * to be able to do the major system redesign to correct this. * * @param domain the domain. * @return a HostAddress, which encompasses the hostname and port that the XMPP server can be * reached at for the specified domain. */ public static HostAddress resolveXMPPDomain(String domain) { if (context == null) { return new HostAddress(domain, 5222); } String key = "c" + domain; // Return item from cache if it exists. if (cache.containsKey(key)) { HostAddress address = (HostAddress) cache.get(key); if (address != null) { return address; } } String bestHost = domain; int bestPort = 5222; int bestPriority = 0; int bestWeight = 0; try { Attributes dnsLookup = context.getAttributes("_xmpp-client._tcp." + domain, new String[] {"SRV"}); Attribute srvAttribute = dnsLookup.get("SRV"); NamingEnumeration srvRecords = srvAttribute.getAll(); while (srvRecords.hasMore()) { String srvRecord = (String) srvRecords.next(); String[] srvRecordEntries = srvRecord.split(" "); int priority = Integer.parseInt(srvRecordEntries[srvRecordEntries.length - 4]); int port = Integer.parseInt(srvRecordEntries[srvRecordEntries.length - 2]); int weight = Integer.parseInt(srvRecordEntries[srvRecordEntries.length - 3]); String host = srvRecordEntries[srvRecordEntries.length - 1]; // Randomize the weight. weight *= Math.random() * weight; if ((bestPriority == 0) || (priority < bestPriority)) { // Choose a server with the lowest priority. bestPriority = priority; bestWeight = weight; bestHost = host; bestPort = port; } else if (priority == bestPriority) { // When we have like priorities then randomly choose a server based on its weight // The weights were randomized above. if (weight > bestWeight) { bestWeight = weight; bestHost = host; bestPort = port; } } } } catch (Exception e) { // Ignore. } // Host entries in DNS should end with a ".". if (bestHost.endsWith(".")) { bestHost = bestHost.substring(0, bestHost.length() - 1); } HostAddress address = new HostAddress(bestHost, bestPort); // Add item to cache. cache.put(key, address); return address; }
public void createResource(Resource resource) throws InternalErrorException { // Create a set of attributes Attributes attributes = new BasicAttributes(); // Create the objectclass to add Attribute objClasses = new BasicAttribute("objectClass"); objClasses.add("top"); objClasses.add("perunResource"); // Add attributes attributes.put(objClasses); attributes.put("cn", resource.getName()); attributes.put("perunResourceId", String.valueOf(resource.getId())); attributes.put("perunFacilityId", String.valueOf(resource.getFacilityId())); attributes.put("perunVoId", String.valueOf(resource.getVoId())); if (resource.getDescription() != null && !resource.getDescription().isEmpty()) attributes.put("description", resource.getDescription()); // Create the entry try { ldapTemplate.bind( getResourceDN(String.valueOf(resource.getVoId()), String.valueOf(resource.getId())), null, attributes); log.debug( "New entry created in LDAP: Resource {} in Vo with Id=" + resource.getVoId() + " and Facility with ID=" + resource.getFacilityId() + ".", resource); } catch (NameNotFoundException e) { throw new InternalErrorException(e); } }
static boolean checkMatchingSearchResult( NamingEnumeration<SearchResult> result, String attrName, Object expValue) throws NamingException { while ((result != null) && result.hasMore()) { SearchResult sr = result.nextElement(); Attributes attrs = sr.getAttributes(); NamingEnumeration<? extends Attribute> attrVals = attrs.getAll(); try { while ((attrVals != null) && attrVals.hasMore()) { Attribute a = attrVals.next(); String attrID = a.getID(); if (!attrName.equalsIgnoreCase(attrID)) { continue; } Object attrVal = a.get(); if (expValue.equals(attrVal)) { return true; } } } finally { if (attrVals != null) { attrVals.close(); } } } return false; }
/** * Compare the given single value with the attribute value(s). * * @param val * @param that * @param ignoreCase * @return -2 for not equal or not present in multi-valued attribute -1 for val < that 0 for * val = that 1 for val > that 2 for val present in multi-valued attr * @throws Throwable */ public int attrValCompare(Object val, Attribute that, boolean ignoreCase) throws Throwable { if (that.size() != 1) { NamingEnumeration ne = that.getAll(); if (ne == null) { return -2; } while (ne.hasMore()) { Object o = ne.next(); if (val instanceof String) { if (compareVal(o, (String) val, ignoreCase) == 0) { return 2; } } else if (o.equals(val)) { return 2; } } return -2; } /** that is a single valued attribute. */ Object o = that.get(); if (val instanceof String) { return compareVal(o, (String) val, ignoreCase); } if (o.equals(val)) { return 0; } return -2; }
@Test public void testLdapExample2() throws Exception { System.out.println("testLdapExample2"); SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] attrIDs = {"cn"}; constraints.setReturningAttributes(attrIDs); Hashtable<String, Object> options = new Hashtable<String, Object>(); options.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory"); options.put("java.naming.provider.url", "ldap://127.0.0.1:10389/"); options.put("java.naming.security.authentication", "simple"); options.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system"); options.put(Context.SECURITY_CREDENTIALS, "secret"); LdapContext ctx = new InitialLdapContext(options, null); String username = "******"; NamingEnumeration<SearchResult> answer = ctx.search("ou=users,o=jtogaf", "uid=" + username, constraints); assertTrue("There is att: ", answer.hasMore()); if (answer.hasMore()) { Attributes attrs = ((SearchResult) answer.next()).getAttributes(); Attribute attr = (Attribute) attrs.get("cn"); System.out.print(attr.get(0)); } }
public UserDTO doLdapAuthentication(UserDTO dto) throws Exception { log.info("INSIDE LDAP AUTHENTICATION 2"); UserDTO ldapDTO = null; String url = "ldap://172.18.20.0:10389"; Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, url); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system"); env.put(Context.SECURITY_CREDENTIALS, "secret"); try { ldapDTO = new UserDTO(); DirContext ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes("cn=" + dto.getUsername() + ",ou=users,ou=system"); Attribute userPassword = attrs.get("userPassword"); String ldapPasswordFromDB = new String((byte[]) userPassword.get()); String md5EncryptedPassword = encryptLdapPassword("md5", dto.getPassword()); if (md5EncryptedPassword.equalsIgnoreCase(ldapPasswordFromDB)) { ldapDTO.setEmployeeId((String) (attrs.get("employeeNumber").get())); ldapDTO.setEmployeeType((String) (attrs.get("employeeType").get())); ldapDTO.setUsername((String) (attrs.get("cn").get())); } ctx.close(); } catch (Exception e) { e.printStackTrace(); } return ldapDTO; }
/** Return the last modified date. */ @Override public long getLastModified() { if (!connected) { // Try to connect (silently) try { connect(); } catch (IOException e) { // Ignore } } if (attributes == null) return 0; Attribute lastModified = attributes.get(ResourceAttributes.LAST_MODIFIED); if (lastModified != null) { try { Date lmDate = (Date) lastModified.get(); return lmDate.getTime(); } catch (Exception e) { // Ignore } } return 0; }
protected Map<String, ArrayList<String>> convertAttributes( NamingEnumeration<? extends Attribute> attributesEnumeration) { Map<String, ArrayList<String>> userInfo = new HashMap<String, ArrayList<String>>(); try { while (attributesEnumeration.hasMore()) { Attribute attr = attributesEnumeration.next(); String id = attr.getID(); ArrayList<String> values = userInfo.get(id); if (values == null) { values = new ArrayList<String>(); userInfo.put(id, values); } // --- loop on all attribute's values NamingEnumeration<?> valueEnum = attr.getAll(); while (valueEnum.hasMore()) { Object value = valueEnum.next(); // Only retrieve String attribute if (value instanceof String) { values.add((String) value); } } } } catch (NamingException e) { e.printStackTrace(); } return userInfo; }
private String getStringAttribute(Attributes user, String name) throws NamingException { Attribute a = user.get(name); if (a == null) return null; Object v = a.get(); if (v == null) return null; return v.toString(); }
private Object getResults(Attribute attr, Object obj) { try { String name = attr.getID().toString(); String Value = attr.get().toString(); Class class1 = obj.getClass(); String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1, name.length()); String[] methodnameIgnot = {"-"}; for (String ignore : methodnameIgnot) { methodName = methodName.replaceAll(ignore, ""); } Method method = class1.getMethod(methodName, String.class); String value = (String) method.invoke(obj, Value); } catch (NamingException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return obj; }
/** * Retrieve the input attributes from the Active Directory for the given search query * * <p>Method getAttributes. * * @param searchBase String * @return List<User> * @throws NamingException */ private final List<User> getAttributes(String searchBase) throws NamingException { LOGGER.info(">> getAttributes()"); NamingEnumeration<SearchResult> results = localInitialLdapContext.search(searchBase, searchFilter, searchctls); List<User> users = new ArrayList<User>(); User user = null; while (results.hasMoreElements()) { user = new User(); SearchResult searchResult = results.next(); Attributes attrs = searchResult.getAttributes(); if (attrs != null && attrs.size() != 0) { Attribute attribute = null; String[] retrieveAttributes = parameters.getRetrieveAttributes(); String[] attributesValues = new String[retrieveAttributes.length]; for (int i = 0; i < retrieveAttributes.length; i++) { attribute = attrs.get(retrieveAttributes[i]); if (attribute != null && attribute.get() != null) { if (!isNullOrEmpty(attribute.get().toString())) { attributesValues[i] = attribute.get().toString(); } } } user.setAttributeValues(attributesValues); } users.add(user); } LOGGER.info("<< getAttributes()"); return users; }
/** * Infer the root DN. * * @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; } }
private LdapUser looukupByFilter(String filter) { SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); DirContext ctxt; try { ctxt = connect(); NamingEnumeration<SearchResult> results = ctxt.search(basedn, filter, sc); if (results.hasMore()) { SearchResult result = results.next(); Attributes attrs = result.getAttributes(); String firstName = attrs.get("givenName").get().toString(); String lastName = attrs.get("sn").get().toString(); String cn = attrs.get("cn").get().toString(); String dn = result.getNameInNamespace(); String forwardAddress = attrs.get("forward").get().toString(); String mailAdress = attrs.get("mail").get().toString(); Attribute addrAttr = attrs.get("privateMail"); if (addrAttr == null) { addrAttr = attrs.get("forward"); } String privateMailAdress = addrAttr.get().toString(); LdapUser user = new LdapUser( dn, firstName, lastName, forwardAddress, mailAdress, privateMailAdress, cn); return user; } } catch (NamingException e) { log.fatal(e); throw new RuntimeException(e); } return null; }
/** Returns the name of the specified header field. */ @Override public String getHeaderField(String name) { if (!connected) { // Try to connect (silently) try { connect(); } catch (IOException e) { // Ignore } } if (attributes == null) return (null); NamingEnumeration<String> attributeEnum = attributes.getIDs(); try { while (attributeEnum.hasMore()) { String attributeID = attributeEnum.next(); if (attributeID.equalsIgnoreCase(name)) { Attribute attribute = attributes.get(attributeID); if (attribute == null) return null; Object attrValue = attribute.get(attribute.size() - 1); return getHeaderValueAsString(attrValue); } } } catch (NamingException ne) { // Shouldn't happen } return (null); }
/** Search criteria based on sn(surname) */ private void searchUsingSubTree() { System.out.println("Inside searchUsingSubTree"); DirContext ctx = LDAPConstants.getLdapContext(); String baseDN = "OU=Staff,OU=Accounts,O=ibo,DC=adld,DC=ibo,DC=org"; SearchControls sc = new SearchControls(); String[] attributeFilter = {"cn", "givenName"}; sc.setReturningAttributes(attributeFilter); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "sn=X*"; // String filter = "(&(sn=R*)(givenName=Sinduja))"; //Examples for search Filters // String filter = "(|(sn=R*)(givenName=Sinduja))"; NamingEnumeration results = null; try { results = ctx.search(baseDN, filter, sc); while (results.hasMore()) { SearchResult sr = (SearchResult) results.next(); Attributes attrs = sr.getAttributes(); Attribute attr = attrs.get("cn"); System.out.print("cn : " + attr.get() + "\n"); attr = attrs.get("givenName"); System.out.print("givenName: " + attr.get() + "\n"); ctx.close(); } } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * @param attributes * @return * @throws NamingException */ protected final Map<String, List<String>> convertToStringAttributesMap(Attributes attributes) throws NamingException { Map<String, List<String>> attributesMap = new HashMap<String, List<String>>(); NamingEnumeration<String> attributeNames = attributes.getIDs(); while (attributeNames.hasMore()) { String attributeName = attributeNames.next(); if (ldapAttributesKey.getPasswordAttributeName().equalsIgnoreCase(attributeName)) { // skip continue; } Attribute attribute = attributes.get(attributeName); int numberOfValues = attribute.size(); for (int i = 0; i < numberOfValues; i++) { String value = (String) attribute.get(i); if (null != value) { value = value.trim(); } List<String> list = safeGetAttributeList(attributesMap, attributeName.toLowerCase()); list.add(value); } } return attributesMap; }
/* goodG2B() - use goodsource and badsink */ public void goodG2B_sink(String data, HttpServletRequest request, HttpServletResponse response) throws Throwable { Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389"); DirContext ctx = new InitialDirContext(env); String search = "(cn=" + data + ")"; /* POTENTIAL FLAW: unsanitized data from untrusted source */ NamingEnumeration<SearchResult> answer = ctx.search("", search, null); while (answer.hasMore()) { SearchResult sr = answer.next(); Attributes a = sr.getAttributes(); NamingEnumeration<?> attrs = a.getAll(); while (attrs.hasMore()) { Attribute attr = (Attribute) attrs.next(); NamingEnumeration<?> values = attr.getAll(); while (values.hasMore()) { response.getWriter().println(" Value: " + values.next().toString()); } } } }
@Override public LdapEntry[] groupSearch(DirContext dirContext, LdapEntry entry) throws IOException, NamingException { Set<LdapEntry> foundEntries = new HashSet<LdapEntry>(); // Load the list of group. Attributes groups = dirContext.getAttributes(entry.getDistinguishedName(), new String[] {groupAttribute}); Attribute groupRef = groups.get(groupAttribute); if (groupRef != null && groupRef.size() > 0) { NamingEnumeration<String> groupRefValues = (NamingEnumeration<String>) groupRef.getAll(); while (groupRefValues.hasMore()) { String distingushedName = groupRefValues.next(); SECURITY_LOGGER.tracef("Group found with distinguishedName=%s", distingushedName); String simpleName = null; if (groupNameAttribute != null) { // Load the Name Attributes groupNameAttrs = dirContext.getAttributes(distingushedName, new String[] {groupNameAttribute}); Attribute groupNameAttr = groupNameAttrs.get(groupNameAttribute); simpleName = (String) groupNameAttr.get(); SECURITY_LOGGER.tracef( "simpleName %s loaded for group with distinguishedName=%s", simpleName, distingushedName); } else { SECURITY_LOGGER.trace("No groupNameAttribute to load simpleName"); } foundEntries.add(new LdapEntry(simpleName, distingushedName)); } } else { SECURITY_LOGGER.tracef("No groups found for %s", entry); } return foundEntries.toArray(new LdapEntry[foundEntries.size()]); }
private LdapEntry convertToLdapEntry(SearchResult searchResult, Attributes attributes) throws NamingException { String simpleName = null; String distinguishedName = null; if (groupNameAttribute != null) { SECURITY_LOGGER.tracef("Getting groupNameAttribute=%s", groupNameAttribute); Attribute groupNameAttr = attributes.get(groupNameAttribute); if (groupNameAttr != null) { simpleName = (String) groupNameAttr.get(); } } if (groupDnAttribute != null) { if ("dn".equals(groupDnAttribute)) { SECURITY_LOGGER.trace("Obtaining dn using getNameInNamespace()"); distinguishedName = searchResult.getNameInNamespace(); } else { SECURITY_LOGGER.tracef("Getting groupDnAttribute=%s", groupDnAttribute); Attribute groupDnAttr = attributes.get(groupDnAttribute); if (groupDnAttr != null) { distinguishedName = (String) groupDnAttr.get(); } } } return new LdapEntry(simpleName, distinguishedName); }
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String param = request.getHeader("vector"); if (param == null) param = ""; String bar; // Simple ? condition that assigns constant to bar on true condition int num = 106; bar = (7 * 18) + num > 200 ? "This_should_always_happen" : param; org.owasp.benchmark.helpers.LDAPManager ads = new org.owasp.benchmark.helpers.LDAPManager(); try { response.setContentType("text/html"); String base = "ou=users,ou=system"; javax.naming.directory.SearchControls sc = new javax.naming.directory.SearchControls(); sc.setSearchScope(javax.naming.directory.SearchControls.SUBTREE_SCOPE); String filter = "(&(objectclass=person))(|(uid=" + bar + ")(street={0}))"; Object[] filters = new Object[] {"The streetz 4 Ms bar"}; javax.naming.directory.DirContext ctx = ads.getDirContext(); javax.naming.directory.InitialDirContext idc = (javax.naming.directory.InitialDirContext) ctx; javax.naming.NamingEnumeration<javax.naming.directory.SearchResult> results = idc.search(base, filter, filters, sc); while (results.hasMore()) { javax.naming.directory.SearchResult sr = (javax.naming.directory.SearchResult) results.next(); javax.naming.directory.Attributes attrs = sr.getAttributes(); javax.naming.directory.Attribute attr = attrs.get("uid"); javax.naming.directory.Attribute attr2 = attrs.get("street"); if (attr != null) { response .getWriter() .write( "LDAP query results:<br>" + " Record found with name " + attr.get() + "<br>" + "Address: " + attr2.get() + "<br>"); System.out.println("record found " + attr.get()); } } } catch (javax.naming.NamingException e) { throw new ServletException(e); } finally { try { ads.closeDirContext(); } catch (Exception e) { throw new ServletException(e); } } }
protected List<User> findUsersByGroupId(LdapUserQueryImpl query) { String baseDn = getDnForGroup(query.getGroupId()); // compose group search filter String groupSearchFilter = "(& " + ldapConfiguration.getGroupSearchFilter() + ")"; NamingEnumeration<SearchResult> enumeration = null; try { enumeration = initialContext.search(baseDn, groupSearchFilter, ldapConfiguration.getSearchControls()); List<String> groupMemberList = new ArrayList<String>(); // first find group while (enumeration.hasMoreElements()) { SearchResult result = enumeration.nextElement(); Attribute memberAttribute = result.getAttributes().get(ldapConfiguration.getGroupMemberAttribute()); if (null != memberAttribute) { NamingEnumeration<?> allMembers = memberAttribute.getAll(); // iterate group members while (allMembers.hasMoreElements() && groupMemberList.size() < query.getMaxResults()) { groupMemberList.add((String) allMembers.nextElement()); } } } List<User> userList = new ArrayList<User>(); String userBaseDn = composeDn(ldapConfiguration.getUserSearchBase(), ldapConfiguration.getBaseDn()); for (String memberId : groupMemberList) { if (ldapConfiguration.isUsePosixGroups()) { query.userId(memberId); } List<User> users = ldapConfiguration.isUsePosixGroups() ? findUsersWithoutGroupId(query, userBaseDn) : findUsersWithoutGroupId(query, memberId); if (users.size() > 0) { userList.add(users.get(0)); } } return userList; } catch (NamingException e) { throw new IdentityProviderException("Could not query for users", e); } finally { try { if (enumeration != null) { enumeration.close(); } } catch (Exception e) { // ignore silently } } }
public static String getIfNotNull(Attributes attrs, String attrID) throws NamingException { Attribute attr = attrs.get(attrID); if (attr != null) { return (String) attr.get(); } else { return ""; } }
// 得到属性 private String getAttribute(Attributes attrs, String attrName) throws NamingException { Attribute attr = attrs.get(attrName); if (attr == null) { return ""; } else { return (String) attr.get(); } }
/** * Search for entry that matches the specific <code>DirectoryQuery</code> conditions * * @param q DirectoryQuery * @return List<DirectoryEntry> * @exception LDAPException */ public List<Identity> search(final LDAPDirectoryQuery q) throws LDAPException { List<Identity> results = new ArrayList<Identity>(); try { DirContext ctx = connection.connect(); if (ctx == null) { throw new LDAPException("directory service not available"); } SearchControls ctls = new SearchControls(); List<String> _aux = new ArrayList<String>(); _aux.add("modifyTimestamp"); _aux.add("*"); ctls.setReturningAttributes(_aux.toArray(new String[_aux.size()])); if (connection.hasCountLimit()) { ctls.setCountLimit(connection.getCountLimit()); } ctls.setSearchScope(connection.getScope()); String filter = getQueryString(ctx, q); NamingEnumeration<SearchResult> answer = ctx.search(baseDN, filter, ctls); while (answer.hasMoreElements()) { SearchResult sr = answer.nextElement(); LDAPDirectoryEntry _e = null; if (sr.getName().isEmpty()) { _e = new LDAPDirectoryEntry(baseDN); } else { _e = new LDAPDirectoryEntry(sr.getNameInNamespace()); /* * _e = new LDAPEntry(sr.getName() + "," + this.baseDN); if(_e.getID().matches( * "^(ldap|ldaps)\\://[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z0-9\\-]+(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\\-\\._\\?\\,\\'/\\\\\\+&%\\$#\\=~])*[^\\.\\,\\)\\(\\s]$" * )) { URL _url = new URL(_e.getID()); _e.setID(_url.getPath()); } */ } @SuppressWarnings("unchecked") NamingEnumeration<Attribute> ne = (NamingEnumeration<Attribute>) sr.getAttributes().getAll(); while (ne.hasMore()) { Attribute att = ne.next(); Object[] attrs = new Object[att.size()]; @SuppressWarnings("unchecked") NamingEnumeration<Object> nea = (NamingEnumeration<Object>) att.getAll(); for (int i = 0; nea.hasMore(); i++) { attrs[i] = nea.next(); } _e.setAttribute(att.getID(), attrs); } results.add(_e); } } catch (NullPointerException e) { _log.log(java.util.logging.Level.ALL, "search() null pointer"); throw new LDAPException("search null pointer"); } catch (NamingException e) { _log.log(java.util.logging.Level.ALL, "search() - " + e.getMessage()); throw new LDAPException(e.getMessage()); } finally { connection.disconnect(); } return results; }
protected String getStringAttributeValue(String attrName, Attributes attributes) throws NamingException { Attribute attribute = attributes.get(attrName); if (attribute != null) { return (String) attribute.get(); } else { return null; } }
/** * @see net.jforum.sso.LoginAuthenticator#validateLogin(java.lang.String, java.lang.String, * java.util.Map) */ public User validateLogin(String username, String password, Map extraParams) { Hashtable environment = this.prepareEnvironment(); StringBuffer principal = new StringBuffer(256) .append(SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_PREFIX)) .append(username) .append(',') .append(SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_SUFFIX)); environment.put(Context.SECURITY_PRINCIPAL, principal.toString()); environment.put(Context.SECURITY_CREDENTIALS, password); DirContext dir = null; try { dir = new InitialDirContext(environment); String lookupPrefix = SystemGlobals.getValue(ConfigKeys.LDAP_LOOKUP_PREFIX); String lookupSuffix = SystemGlobals.getValue(ConfigKeys.LDAP_LOOKUP_SUFFIX); if (lookupPrefix == null || lookupPrefix.length() == 0) { lookupPrefix = SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_PREFIX); } if (lookupSuffix == null || lookupSuffix.length() == 0) { lookupSuffix = SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_SUFFIX); } String lookupPrincipal = lookupPrefix + username + "," + lookupSuffix; Attribute att = dir.getAttributes(lookupPrincipal) .get(SystemGlobals.getValue(ConfigKeys.LDAP_FIELD_EMAIL)); SSOUtils utils = new SSOUtils(); if (!utils.userExists(username)) { String email = att != null ? (String) att.get() : "noemail"; utils.register("ldap", email); } return utils.getUser(); } catch (AuthenticationException e) { return null; } catch (NamingException e) { return null; } finally { if (dir != null) { try { dir.close(); } catch (NamingException e) { // close jndi context } } } }