List of usage examples for javax.naming.directory SearchResult getAttributes
public Attributes getAttributes()
From source file:org.jasig.portal.security.provider.SimpleLdapSecurityContext.java
/** * Authenticates the user.//ww w.j a va 2 s . com */ public synchronized void authenticate() throws PortalSecurityException { this.isauth = false; ILdapServer ldapConn; String propFile = ctxProperties.getProperty(LDAP_PROPERTIES_CONNECTION_NAME); if (propFile != null && propFile.length() > 0) ldapConn = LdapServices.getLdapServer(propFile); else ldapConn = LdapServices.getDefaultLdapServer(); String creds = new String(this.myOpaqueCredentials.credentialstring); if (this.myPrincipal.UID != null && !this.myPrincipal.UID.trim().equals("") && this.myOpaqueCredentials.credentialstring != null && !creds.trim().equals("")) { DirContext conn = null; NamingEnumeration results = null; StringBuffer user = new StringBuffer("("); String first_name = null; String last_name = null; user.append(ldapConn.getUidAttribute()).append("="); user.append(this.myPrincipal.UID).append(")"); if (log.isDebugEnabled()) log.debug("SimpleLdapSecurityContext: Looking for " + user.toString()); try { conn = ldapConn.getConnection(); // set up search controls SearchControls searchCtls = new SearchControls(); searchCtls.setReturningAttributes(attributes); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // do lookup if (conn != null) { try { results = conn.search(ldapConn.getBaseDN(), user.toString(), searchCtls); if (results != null) { if (!results.hasMore()) log.error("SimpleLdapSecurityContext: user not found , " + this.myPrincipal.UID); while (results != null && results.hasMore()) { SearchResult entry = (SearchResult) results.next(); StringBuffer dnBuffer = new StringBuffer(); dnBuffer.append(entry.getName()).append(", "); dnBuffer.append(ldapConn.getBaseDN()); Attributes attrs = entry.getAttributes(); first_name = getAttributeValue(attrs, ATTR_FIRSTNAME); last_name = getAttributeValue(attrs, ATTR_LASTNAME); // re-bind as user conn.removeFromEnvironment(javax.naming.Context.SECURITY_PRINCIPAL); conn.removeFromEnvironment(javax.naming.Context.SECURITY_CREDENTIALS); conn.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, dnBuffer.toString()); conn.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS, this.myOpaqueCredentials.credentialstring); searchCtls = new SearchControls(); searchCtls.setReturningAttributes(new String[0]); searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE); String attrSearch = "(" + ldapConn.getUidAttribute() + "=*)"; log.debug("SimpleLdapSecurityContext: Looking in " + dnBuffer.toString() + " for " + attrSearch); conn.search(dnBuffer.toString(), attrSearch, searchCtls); this.isauth = true; this.myPrincipal.FullName = first_name + " " + last_name; log.debug("SimpleLdapSecurityContext: User " + this.myPrincipal.UID + " (" + this.myPrincipal.FullName + ") is authenticated"); // Since LDAP is case-insensitive with respect to uid, force // user name to lower case for use by the portal this.myPrincipal.UID = this.myPrincipal.UID.toLowerCase(); } // while (results != null && results.hasMore()) } else { log.error("SimpleLdapSecurityContext: No such user: " + this.myPrincipal.UID); } } catch (AuthenticationException ae) { log.info("SimpleLdapSecurityContext: Password invalid for user: " + this.myPrincipal.UID); } catch (Exception e) { log.error("SimpleLdapSecurityContext: LDAP Error with user: " + this.myPrincipal.UID + "; ", e); throw new PortalSecurityException("SimpleLdapSecurityContext: LDAP Error" + e + " with user: " + this.myPrincipal.UID); } finally { ldapConn.releaseConnection(conn); } } else { log.error("LDAP Server Connection unavalable"); } } catch (final NamingException ne) { log.error("Error geting connection to LDAP server.", ne); } } else { log.error("Principal or OpaqueCredentials not initialized prior to authenticate"); } // Ok...we are now ready to authenticate all of our subcontexts. super.authenticate(); return; }
From source file:ru.efo.security.ADUserDetailsService.java
private ADUserDetails loadUserByUsername(DirContext context, String username, String password) throws UsernameNotFoundException { try {/*from w w w . j av a 2 s.c o m*/ SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); // search for username NamingEnumeration<SearchResult> renum = context.search(userSearchBase, "(&(objectClass=user)(sAMAccountName={0}))", new Object[] { username }, controls); if (!renum.hasMoreElements()) { throw new UsernameNotFoundException("User '" + username + "' is not exist"); } SearchResult result = renum.next(); final Attributes attributes = result.getAttributes(); // User's display name String displayName = null; Attribute attr = attributes.get(displayNameAttribute); if (attr != null) { displayName = attr.get().toString(); } if (!StringUtils.hasText(displayName)) displayName = username; logger.log(Level.FINE, "Display name: " + displayName); // User's email String email = null; attr = attributes.get(emailAttribute); if (attr != null) { email = attr.get().toString(); } logger.log(Level.FINE, "E-mail: " + email); // User's phone number String phone = null; attr = attributes.get(phoneAttribute); if (attr != null) { phone = attr.get().toString(); } logger.log(Level.FINE, "Phone: " + phone); // Is user blocked boolean blocked = false; attr = attributes.get("userAccountControl"); if (attr != null) { blocked = (Long.parseLong(attr.get().toString()) & 2) != 0; } logger.log(Level.FINE, "Blocked: " + blocked); // describe roles and groups final Set<String> roles = new TreeSet<>(); final Set<String> groups = new TreeSet<>(); Attribute memberOf = attributes.get("memberOf"); describeRoles(context, memberOf, groups, roles); // Describe user primary role Attribute attrPrimaryGroupId = attributes.get("primaryGroupId"); Attribute attrObjectSid = attributes.get("objectSid"); if (attrPrimaryGroupId != null && attrObjectSid != null) { int primaryGroupId = Integer.parseInt(attrPrimaryGroupId.get().toString()); byte[] objectSid = (byte[]) attrObjectSid.get(); // add primary group RID for (int i = 0; i < 4; i++) { objectSid[objectSid.length - 4 + i] = (byte) (primaryGroupId & 0xFF); primaryGroupId >>= 8; } StringBuilder tmp = new StringBuilder(); for (int i = 2; i <= 7; i++) { tmp.append(Integer.toHexString(objectSid[i] & 0xFF)); } // convert objectSid to String StringBuilder sidBuilder = new StringBuilder("S-").append(objectSid[0]).append("-") .append(Long.parseLong(tmp.toString(), 16)); // the sub authorities count int count = objectSid[1]; // add authorities for (int i = 0; i < count; i++) { tmp.setLength(0); int offset = i * 4; tmp.append(String.format("%02X%02X%02X%02X", (objectSid[11 + offset] & 0xFF), (objectSid[10 + offset] & 0xFF), (objectSid[9 + offset] & 0xFF), (objectSid[8 + offset] & 0xFF))); sidBuilder.append('-').append(Long.parseLong(tmp.toString(), 16)); } SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); renum = context.search(userSearchBase, "(&(objectClass=group)(objectSid={0}))", new Object[] { sidBuilder.toString() }, searchControls); if (renum.hasMoreElements()) { result = renum.next(); attr = result.getAttributes().get("distinguishedName"); describeRoles(context, attr, groups, roles); } } return new ADUserDetails(username, password, displayName, email, phone, blocked, groups, roles); } catch (NamingException ex) { logger.log(Level.SEVERE, "Could not find user '" + username + "'", ex); throw new UsernameNotFoundException(ex.getMessage()); } }
From source file:com.predic8.membrane.core.interceptor.authentication.session.LDAPUserDataProvider.java
private String searchUser(String login, HashMap<String, String> userAttrs, DirContext ctx) throws NamingException { String uid;//from ww w . ja v a2 s . c om SearchControls ctls = new SearchControls(); ctls.setReturningObjFlag(true); ctls.setSearchScope(searchScope); String search = searchPattern.replaceAll(Pattern.quote("%LOGIN%"), escapeLDAPSearchFilter(login)); log.debug("Searching LDAP for " + search); NamingEnumeration<SearchResult> answer = ctx.search(base, search, ctls); try { if (!answer.hasMore()) throw new NoSuchElementException(); log.debug("LDAP returned >=1 record."); SearchResult result = answer.next(); uid = result.getName(); for (Map.Entry<String, String> e : attributeMap.entrySet()) { log.debug("found LDAP attribute: " + e.getKey()); Attribute a = result.getAttributes().get(e.getKey()); if (a != null) userAttrs.put(e.getValue(), a.get().toString()); } } finally { answer.close(); } return uid; }
From source file:org.infoscoop.account.ldap.LDAPAccountManager.java
private List searchGroupMember(DirContext context, Map filters) throws NamingException { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); Set userList = new HashSet(); String filter = buildFilter(filters); if (log.isInfoEnabled()) log.info("Search User from " + userBase + " by " + filter); NamingEnumeration searchResultEnum = context.search(this.groupBase, filter, searchControls); while (searchResultEnum.hasMore()) { SearchResult searchResult = (SearchResult) searchResultEnum.next(); Attributes attrs = searchResult.getAttributes(); String dn = searchResult.getName() + "," + groupBase; String uniquememberAttrName = "uniqueMember"; if (this.propAttrMap.containsKey("org_member")) { try { uniquememberAttrName = (String) this.propAttrMap.get("org_member"); } catch (Exception ex) { //ignore }//from w w w . ja v a 2 s . c o m } Attribute uniquememberAttr = attrs.get(uniquememberAttrName); if (uniquememberAttr == null) continue; NamingEnumeration memberDNs = uniquememberAttr.getAll(); while (memberDNs.hasMoreElements()) { //System.out.println(memberDNs[j]); userList.add(memberDNs.next());//DN of user } } List members = new ArrayList(); for (Iterator userDns = userList.iterator(); userDns.hasNext();) { /* Next directory entry */ String userDn = (String) userDns.next(); Attributes userEntry = null; try { userEntry = context.getAttributes(userDn);//DN of user } catch (Exception e) { log.error(userDn + ": " + e.getMessage()); } if (userEntry == null) continue; LDAPAccount user = createLDAPUser(userDn, userEntry); if (user.getUid() == null) continue; members.add(user); } return members; }
From source file:org.apache.directory.server.tools.commands.exportcmd.ExportCommandExecutor.java
private void execute() throws Exception { // Connecting to server and retreiving entries NamingEnumeration entries = connectToServerAndGetEntries(); // Creating destination file File destionationFile = new File(ldifFileName); // Deleting the destination file if it already exists if (destionationFile.exists()) { destionationFile.delete();/*from w w w . ja va2s . com*/ } // Creating the writer to generate the LDIF file FileWriter fw = new FileWriter(ldifFileName, true); BufferedWriter writer = new BufferedWriter(fw); OtcLdifComposerImpl composer = new OtcLdifComposerImpl(); MultiValueMap map = new MultiValueMap(); // MultiMap map = new MultiMap() { // // FIXME Stop forking commons-collections. // private final MultiValueMap map = new MultiValueMap(); // // public Object remove(Object arg0, Object arg1) { // return map.remove(arg0, arg1); // } // // public int size() { // return map.size(); // } // // public Object get(Object arg0) { // return map.get(arg0); // } // // public boolean containsValue(Object arg0) { // return map.containsValue(arg0); // } // // public Object put(Object arg0, Object arg1) { // return map.put(arg0, arg1); // } // // public Object remove(Object arg0) { // return map.remove(arg0); // } // // public Collection values() { // return map.values(); // } // // public boolean isEmpty() { // return map.isEmpty(); // } // // public boolean containsKey(Object key) { // return map.containsKey(key); // } // // public void putAll(Map arg0) { // map.putAll(arg0); // } // // public void clear() { // map.clear(); // } // // public Set keySet() { // return map.keySet(); // } // // public Set entrySet() { // return map.entrySet(); // } // }; int entriesCounter = 1; long t0 = System.currentTimeMillis(); while (entries.hasMoreElements()) { SearchResult sr = (SearchResult) entries.nextElement(); Attributes attributes = sr.getAttributes(); NamingEnumeration attributesEnumeration = attributes.getAll(); map.clear(); while (attributesEnumeration.hasMoreElements()) { Attribute attr = (Attribute) attributesEnumeration.nextElement(); NamingEnumeration e2 = null; e2 = attr.getAll(); while (e2.hasMoreElements()) { Object value = e2.nextElement(); map.put(attr.getID(), value); } } // Writing entry in the file writer.write("dn: " + sr.getNameInNamespace() + "\n"); writer.write(composer.compose(map) + "\n"); notifyEntryWrittenListener(sr.getNameInNamespace()); entriesCounter++; if (entriesCounter % 10 == 0) { notifyOutputListener(new Character('.')); } if (entriesCounter % 500 == 0) { notifyOutputListener("" + entriesCounter); } } writer.flush(); writer.close(); fw.close(); long t1 = System.currentTimeMillis(); notifyOutputListener("Done!"); notifyOutputListener(entriesCounter + " entries exported in " + ((t1 - t0) / 1000) + " seconds"); }
From source file:org.lsc.beans.LscBean.java
/** * Set a bean from an LDAP entry//from ww w .ja va 2s . c om * * @param entry * the LDAP entry * @param baseDn * the base Dn used to set the right Dn * @param c * class to instantiate * @return the bean * @throws NamingException * thrown if a directory exception is encountered while looking * at the entry */ public static LscBean getInstance(final SearchResult entry, final String baseDn, final Class<?> c) throws NamingException { try { if (entry != null) { LscBean ab = (LscBean) c.newInstance(); String dn = entry.getName(); if ((dn.length() > 0) && (dn.charAt(0) == '"') && (dn.charAt(dn.length() - 1) == '"')) { dn = dn.substring(1, dn.length() - 1); } if (dn.startsWith("ldap://")) { ab.setDistinguishName(entry.getNameInNamespace()); } else { // Manually concat baseDn because getNameInNamespace returns // a differently escaped DN, causing LSC to detect a MODRDN if ((baseDn != null) && (baseDn.length() > 0)) { if (dn.length() > 0) { ab.setDistinguishName(dn + "," + baseDn); } else { ab.setDistinguishName(baseDn); } } else { ab.setDistinguishName(dn); } } NamingEnumeration<?> ne = entry.getAttributes().getAll(); while (ne.hasMore()) { ab.setAttribute((Attribute) ne.next()); } return ab; } else { return null; } } catch (InstantiationException ie) { LOGGER.error(ie.toString()); LOGGER.debug(ie.toString(), ie); } catch (IllegalAccessException iae) { LOGGER.error(iae.toString()); LOGGER.debug(iae.toString(), iae); } return null; }
From source file:org.projectforge.business.ldap.LdapDao.java
public T findById(final DirContext ctx, final Object id, final String... organizationalUnits) throws NamingException { NamingEnumeration<?> results = null; final SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); final String searchBase = getSearchBase(organizationalUnits); final String args = "(&(objectClass=" + getObjectClass() + ")(" + getIdAttrId() + "=" + buildId(id) + "))"; results = ctx.search(searchBase, args, controls); if (results.hasMore() == false) { return null; }// ww w. ja va 2 s.c o m final SearchResult searchResult = (SearchResult) results.next(); final String dn = searchResult.getName(); final Attributes attributes = searchResult.getAttributes(); if (results.hasMore() == true) { log.error("Oups, found entries with multiple id's: " + getObjectClass() + "." + id); } return mapToObject(dn, searchBase, attributes); }
From source file:org.infoscoop.account.ldap.LDAPAccountManager.java
private void setGroup(DirContext context, LDAPAccount user) throws NamingException { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); //create the filter of group Map filters = new HashMap(); String uniqueMemberAttrName = "uniquemember"; if (this.propAttrMap.containsKey("org_member")) uniqueMemberAttrName = (String) this.propAttrMap.get("org_member"); filters.put(uniqueMemberAttrName, user.getDn()); String grpFilter = buildGroupFilterByDN(filters); NamingEnumeration grpRes = context.search(groupBase, grpFilter, searchControls); List grpList = new ArrayList(); while (grpRes.hasMoreElements()) { SearchResult findGrpEntry = (SearchResult) grpRes.next(); if (log.isDebugEnabled()) log.debug("Found Groups: " + findGrpEntry.getAttributes().toString()); String grpdn = findGrpEntry.getName() + "," + groupBase; grpList.add(createLDAPGroup(grpdn, findGrpEntry.getAttributes())); }/* www . j a v a2s .c om*/ IGroup[] igroup = new IGroup[grpList.size()]; for (int i = 0; i < igroup.length; i++) { igroup[i] = (IGroup) grpList.get(i); } user.setGroups(igroup); }
From source file:org.projectforge.business.ldap.LdapDao.java
public List<T> findAll(final DirContext ctx, final String organizationalUnit) throws NamingException { final LinkedList<T> list = new LinkedList<T>(); NamingEnumeration<?> results = null; final SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); final String searchBase = getSearchBase(organizationalUnit); results = ctx.search(searchBase, "(objectclass=" + getObjectClass() + ")", controls); while (results.hasMore()) { final SearchResult searchResult = (SearchResult) results.next(); final String dn = searchResult.getName(); final Attributes attributes = searchResult.getAttributes(); list.add(mapToObject(dn, searchBase, attributes)); }/*w ww . j a v a 2 s .c om*/ return list; }
From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java
/** * Get the value of an attribute from a search result * /*from w w w. j av a 2 s .c o m*/ * @param attrName * The name of the attribute that we're interested in * @param sr * The search result * @return The attribute value * @throws NamingException */ private String getAttrValue(String attrName, SearchResult sr) throws NamingException { // Get all attributes Attributes entry = sr.getAttributes(); // Get the attribute value and return Attribute attrValues = entry.get(attrName); if (attrValues == null) return null; String[] strArr = attrValues.toString().split(":"); return strArr[1].trim(); }