List of usage examples for javax.naming.directory SearchControls setReturningAttributes
public void setReturningAttributes(String[] attrs)
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static String getOrgDN(String organisation, String countryCode) { NamingEnumeration results = null; DirContext ctx = null;//ww w . j av a 2 s . co m String dn = null; try { ctx = getContext(); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); String retAttrs[] = { "dn" }; controls.setReturningAttributes(retAttrs); ResourceBundle rb = ResourceBundle.getBundle("ldap"); results = ctx.search("c=" + countryCode + "," + rb.getString("organisationsRoot"), "(&(objectclass=organization)(o=" + organisation + "))", controls); if (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); dn = searchResult.getNameInNamespace(); } } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { throw new RuntimeException(e); } finally { if (results != null) { try { results.close(); } catch (Exception e) { // Never mind this. } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { // Never mind this. } } } return dn; }
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static LDAPUser getIfValidUser(String cn, String password) { LDAPUser user = null;//from w w w . j av a2 s . c om NamingEnumeration results = null; DirContext ctx = null; try { ctx = getAuthContext(cn, password); SearchControls controls = new SearchControls(); String retAttrs[] = { "cn", "sn", "givenName", "title", "registeredAddress", "mail", "memberOf", "createTimestamp" }; controls.setReturningAttributes(retAttrs); controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); ResourceBundle rb = ResourceBundle.getBundle("ldap"); results = ctx.search(rb.getString("peopleRoot"), "(cn=" + cn + ")", controls); if (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); user = new LDAPUser(); if (attributes.get("cn") != null) user.setUsername((String) attributes.get("cn").get()); if (attributes.get("sn") != null) user.setSurname((String) attributes.get("sn").get()); if (attributes.get("givenName") != null) user.setGivenname((String) attributes.get("givenName").get()); if (attributes.get("title") != null) user.setTitle((String) attributes.get("title").get()); if (attributes.get("registeredAddress") != null) user.setPreferredMail((String) attributes.get("registeredAddress").get(0)); if (attributes.get("mail") != null) { String mails = ""; for (int i = 0; i < attributes.get("mail").size(); i++) { if (i != 0) mails = mails + ", "; mails = mails + (String) attributes.get("mail").get(i); } user.setAdditionalMails(mails); } if (attributes.get("memberOf") != null) { for (int i = 0; i < attributes.get("memberOf").size(); i++) { user.addGroup((String) attributes.get("memberOf").get(i)); } } if (attributes.get("createTimestamp") != null) { String time = (String) attributes.get("createTimestamp").get(); DateFormat ldapData = new SimpleDateFormat("yyyyMMddHHmmss"); user.setCreationTime(ldapData.parse(time)); } } } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { _log.error(e); } catch (ParseException ex) { _log.error(ex); } finally { if (results != null) { try { results.close(); } catch (Exception e) { // Never mind this. } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { // Never mind this. } } } return user; }
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static LDAPUser getUser(String cn) { LDAPUser user = null;// w w w . j ava 2 s. c o m NamingEnumeration results = null; DirContext ctx = null; try { ctx = getContext(); SearchControls controls = new SearchControls(); String retAttrs[] = { "cn", "sn", "givenName", "title", "registeredAddress", "mail", "memberOf", "createTimestamp" }; controls.setReturningAttributes(retAttrs); controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); ResourceBundle rb = ResourceBundle.getBundle("ldap"); results = ctx.search(rb.getString("peopleRoot"), "(cn=" + cn + ")", controls); if (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); user = new LDAPUser(); if (attributes.get("cn") != null) user.setUsername((String) attributes.get("cn").get()); if (attributes.get("sn") != null) user.setSurname((String) attributes.get("sn").get()); if (attributes.get("givenName") != null) user.setGivenname((String) attributes.get("givenName").get()); if (attributes.get("title") != null) user.setTitle((String) attributes.get("title").get()); if (attributes.get("registeredAddress") != null) user.setPreferredMail((String) attributes.get("registeredAddress").get(0)); if (attributes.get("mail") != null) { String mails = ""; for (int i = 0; i < attributes.get("mail").size(); i++) { if (i != 0) mails = mails + ", "; mails = mails + (String) attributes.get("mail").get(i); } user.setAdditionalMails(mails); } if (attributes.get("memberOf") != null) { for (int i = 0; i < attributes.get("memberOf").size(); i++) { user.addGroup((String) attributes.get("memberOf").get(i)); } } if (attributes.get("createTimestamp") != null) { String time = (String) attributes.get("createTimestamp").get(); DateFormat ldapData = new SimpleDateFormat("yyyyMMddHHmmss"); user.setCreationTime(ldapData.parse(time)); } } } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { _log.error(e); } catch (ParseException ex) { _log.error(ex); } finally { if (results != null) { try { results.close(); } catch (Exception e) { // Never mind this. } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { // Never mind this. } } } return user; }
From source file:com.seyren.core.security.ldap.LdapUserManagement.java
@Override public String[] autoCompleteUsers(String name) { List<String> users = new ArrayList<String>(); try {/*from w ww . jav a 2s . c o m*/ DirContext readOnlyContext = contextSource.getReadOnlyContext(); SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] attrIDs = { USERNAME }; ctls.setReturningAttributes(attrIDs); NamingEnumeration<SearchResult> results = readOnlyContext.search("", "(sAMAccountName=" + name + "*)", ctls); while (results.hasMore()) { SearchResult rslt = results.next(); Attributes attrs = rslt.getAttributes(); if (attrs.get(USERNAME) != null) { users.add((String) attrs.get(USERNAME).get()); } } } catch (NamingException e) { } return users.toArray(new String[users.size()]); }
From source file:fi.koku.services.utility.authorization.impl.GroupServiceLDAPImpl.java
private List<LdapPerson> getPersonDnsByPics(List<String> pics) { SearchControls ctrl = new SearchControls(); ctrl.setReturningAttributes(new String[] { "uid" }); ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE); String q = getPersonsQuery(pics); logger.debug("getPersonDnsByPics: query: " + q.toString()); List<LdapPerson> persons = ldapTemplate.search("", q, ctrl, new LdapPersonMapper(), new DirContextProcessorNoop()); logger.debug("persons: " + persons.size()); return persons; }
From source file:io.lavagna.service.Ldap.java
public Pair<Boolean, List<String>> authenticateWithParams(String providerUrl, String ldapManagerDn, String ldapManagerPwd, String base, String filter, String username, String password) { requireNonNull(username);// w w w .j a va 2 s . co m requireNonNull(password); List<String> msgs = new ArrayList<>(); msgs.add(format("connecting to %s with managerDn %s", providerUrl, ldapManagerDn)); try (InitialDirContextCloseable dctx = ldapConnection.context(providerUrl, ldapManagerDn, ldapManagerPwd)) { msgs.add(format("connected [ok]")); msgs.add(format("now searching user \"%s\" with base %s and filter %s", username, base, filter)); SearchControls sc = new SearchControls(); sc.setReturningAttributes(null); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); List<SearchResult> srs = Ldap.search(dctx, base, new MessageFormat(filter).format(new Object[] { Ldap.escapeLDAPSearchFilter(username) }), sc); if (srs.size() != 1) { String msg = format("error for username \"%s\" we have %d results instead of 1 [error]", username, srs.size()); msgs.add(msg); LOG.info(msg, username, srs.size()); return Pair.Companion.of(false, msgs); } msgs.add("user found, now will connect with given password [ok]"); SearchResult sr = srs.get(0); try (InitialDirContextCloseable uctx = ldapConnection.context(providerUrl, sr.getNameInNamespace(), password)) { msgs.add("user authenticated, everything seems ok [ok]"); return Pair.Companion.of(true, msgs); } catch (NamingException e) { String msg = format("error while checking with username \"%s\" with message: %s [error]", username, e.getMessage()); msgs.add(msg); LOG.info(msg, e); return Pair.Companion.of(false, msgs); } } catch (Throwable e) { String errMsg = format( "error while opening the connection with message: %s [error], check the logs for a more complete trace", e.getMessage()); msgs.add(errMsg); msgs.add("Full stacktrace is:"); msgs.add(ExceptionUtils.getStackTrace(e)); LOG.error(errMsg, e); return Pair.Companion.of(false, msgs); } }
From source file:org.jasig.cas.adaptors.ldap.BindLdapAuthenticationHandler.java
private SearchControls getSearchControls() { final SearchControls constraints = new SearchControls(); constraints.setSearchScope(this.scope); constraints.setReturningAttributes(new String[0]); constraints.setTimeLimit(this.timeout); constraints.setCountLimit(this.maxNumberResults); return constraints; }
From source file:info.jtrac.acegi.JtracLdapAuthenticationProvider.java
/** * displayName and mail are returned always, the map allows us to support * getting arbitrary properties in the future, hopefully *///w ww . j a va2 s .c o m public Map<String, String> bind(String loginName, String password) throws Exception { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapUrl); env.put(Context.SECURITY_AUTHENTICATION, "simple"); LdapContext ctx = null; if (activeDirectoryDomain != null) { // we are using Active Directory Control[] controls = new Control[] { control }; ctx = new InitialLdapContext(env, controls); logger.debug("Active Directory LDAP context initialized"); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, activeDirectoryDomain + "\\" + loginName); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password); // javax.naming.AuthenticationException ctx.reconnect(controls); logger.debug("Active Directory LDAP bind successful"); } else { // standard LDAP env.put(Context.SECURITY_PRINCIPAL, searchKey + "=" + loginName + "," + searchBase); env.put(Context.SECURITY_CREDENTIALS, password); ctx = new InitialLdapContext(env, null); logger.debug("Standard LDAP bind successful"); } SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(returningAttributes); NamingEnumeration results = ctx.search(searchBase, searchKey + "=" + loginName, sc); while (results.hasMoreElements()) { SearchResult sr = (SearchResult) results.next(); Attributes attrs = sr.getAttributes(); logger.debug("attributes: " + attrs); Map<String, String> map = new HashMap<String, String>(returningAttributes.length); for (String key : returningAttributes) { Attribute attr = attrs.get(key); if (attr != null) { map.put(key, (String) attr.get()); } } return map; // there should be only one anyway } // if we reached here, there was no search result throw new Exception("no results returned from ldap"); }
From source file:com.healthcit.cacure.businessdelegates.LdapUserManager.java
public List<UserCredentials> getAllUsers() { List<UserCredentials> userCredentials = new ArrayList<UserCredentials>(); try {/* w w w . j av a2s . co m*/ SearchControls searchCtls = new SearchControls(); String returnedAtts[] = { "uid" }; searchCtls.setReturningAttributes(returnedAtts); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = "(&(objectClass=person))"; NamingEnumeration<SearchResult> elements = contextSource.getReadOnlyContext().search("", searchFilter, searchCtls); while (elements.hasMoreElements()) { DistinguishedName dn = new DistinguishedName(elements.nextElement().getName()); String userName = dn.getValue("uid"); userCredentials.add(getUserFromDatabase(userName)); } } catch (org.springframework.ldap.NamingException e) { e.printStackTrace(); return null; } catch (NamingException e) { e.printStackTrace(); return null; } return userCredentials; }