List of usage examples for javax.naming.directory SearchResult getAttributes
public Attributes getAttributes()
From source file:jp.ikedam.jenkins.plugins.ldap_sasl.SearchGroupResolver.java
/** * Resolves groups by querying the LDAP directory. * //from ww w .j a v a 2 s . c o m * Never return null in any case. Returns empty list instead. * * @param ctx * @param dn * @param username * @return List of authorities (not null) * @see jp.ikedam.jenkins.plugins.ldap_sasl.GroupResolver#resolveGroup(javax.naming.ldap.LdapContext, java.lang.String, java.lang.String) */ @Override public List<GrantedAuthority> resolveGroup(LdapContext ctx, String dn, String username) { List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); Logger logger = getLogger(); if (dn == null) { logger.warning("Group cannot be resolved: DN of the user is not resolved!"); return authorities; } try { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); logger.fine(String.format("Searching groups base=%s, dn=%s", getSearchBase(), dn)); NamingEnumeration<SearchResult> entries = ctx.search((getSearchBase() != null) ? getSearchBase() : "", getGroupSearchQuery(dn), searchControls); while (entries.hasMore()) { SearchResult entry = entries.next(); String groupName = entry.getAttributes().get("cn").get().toString(); if (getPrefix() != null) { groupName = getPrefix() + groupName; } authorities.add(new GrantedAuthorityImpl(groupName)); logger.fine(String.format("group: %s", groupName)); } entries.close(); } catch (NamingException e) { logger.log(Level.WARNING, "Failed to search groups", e); } return authorities; }
From source file:de.tuttas.util.LDAPUtil.java
/** * Benutzer aus der LDAP Abfragen/*from w ww . java 2s. co m*/ * * @param username Benutzername * @param password Kennwort * @return der Benutzer * @throws Exception Wenn etwas schief ging */ public LDAPUser authenticateJndi(String username, String password) throws Exception { // Anbindung ans LDAP Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, Config.getInstance().ldaphost); props.put(Context.SECURITY_PRINCIPAL, Config.getInstance().bindUser);//adminuser - User with special priviledge, dn user props.put(Context.SECURITY_CREDENTIALS, Config.getInstance().bindPassword);//dn user password try { context = new InitialDirContext(props); ctrls = new SearchControls(); ctrls.setReturningAttributes(new String[] { "description", "mail", "sn", "initials", "givenName", "memberOf", "userPrincipalName", "distinguishedName" }); ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE); } catch (NamingException ex) { Logger.getLogger(LDAPUtil.class.getName()).log(Level.SEVERE, null, ex); } NamingEnumeration<javax.naming.directory.SearchResult> answers = context .search(Config.getInstance().userContext, "(cn=" + username + ")", ctrls); Log.d("answers=" + answers); Log.d("answers=" + answers.hasMore()); if (!answers.hasMore()) { return null; } javax.naming.directory.SearchResult result = answers.nextElement(); try { for (NamingEnumeration ae = result.getAttributes().getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); Log.d("attribute: " + attr.getID()); /* print each value */ for (NamingEnumeration e = attr.getAll(); e.hasMore(); System.out.println("value: " + e.next())) ; } } catch (NamingException e) { e.printStackTrace(); } String inititials = ""; if (result.getAttributes().get("initials") != null) { inititials = result.getAttributes().get("initials").getAll().next().toString(); } LDAPUser u; if (result.getAttributes().get("mail") == null) { u = new LDAPUser(result.getAttributes().get("sn").getAll().next().toString(), result.getAttributes().get("givenName").getAll().next().toString(), "", inititials); } else { u = new LDAPUser(result.getAttributes().get("sn").getAll().next().toString(), result.getAttributes().get("givenName").getAll().next().toString(), result.getAttributes().get("mail").getAll().next().toString(), inititials); } String dName = result.getAttributes().get("distinguishedName").getAll().next().toString(); Log.d("dName=" + dName); if (dName.contains("OU=Lehrer")) { Log.d("Ich bin ein Lehrer"); u.setRole(Roles.toString(Roles.LEHRER)); } else { Log.d("Ich bin ein Schler"); u.setRole(Roles.toString(Roles.SCHUELER)); if (result.getAttributes().get("memberOf") != null) { String memberOf = result.getAttributes().get("memberOf").getAll().next().toString(); String courseName = memberOf.split(",")[0]; courseName = courseName.substring(courseName.indexOf("=") + 1); Log.d("Name der Klasse ist " + courseName); u.setCourse(courseName); } } String user = result.getNameInNamespace(); try { props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, Config.getInstance().ldaphost); props.put(Context.SECURITY_PRINCIPAL, user); props.put(Context.SECURITY_CREDENTIALS, password); context = new InitialDirContext(props); } catch (Exception e) { return null; } return u; }
From source file:org.hyperic.hq.plugin.openldap.OpenLDAPMeasurementPlugin.java
private MetricValue getMetric(Metric metric, String tree, String attr) throws MetricNotFoundException, NamingException { NamingEnumeration enumer = null; try {/*from ww w . j ava 2 s.c om*/ String[] a = { attr }; SearchControls cons = new SearchControls(); cons.setSearchScope(SearchControls.OBJECT_SCOPE); cons.setReturningAttributes(a); enumer = getDirContext(metric.getProperties()).search(tree, "(&(objectClass=*))", cons); while (enumer.hasMore()) { SearchResult searchresult = (SearchResult) enumer.next(); Attributes attrs = searchresult.getAttributes(); Attribute val; if (null != (val = attrs.get(attr))) { return new MetricValue(new Double(val.get().toString()), System.currentTimeMillis()); } } throw new MetricNotFoundException(""); } finally { if (enumer != null) { enumer.close(); } } }
From source file:org.apache.hadoop.hdfsproxy.LdapIpDirFilter.java
/** * check if client's ip is listed in the Ldap Roles if yes, return true and * update ldapent. if not, return false//from w w w . j ava 2s . c om * */ @SuppressWarnings("unchecked") private boolean getLdapRoleEntryFromUserIp(String userIp, LdapRoleEntry ldapent) throws NamingException { String ipMember = hdfsIpSchemaStrPrefix + userIp; Attributes matchAttrs = new BasicAttributes(true); matchAttrs.put(new BasicAttribute(hdfsIpSchemaStr, ipMember)); matchAttrs.put(new BasicAttribute(hdfsUidSchemaStr)); matchAttrs.put(new BasicAttribute(hdfsPathSchemaStr)); String[] attrIDs = { hdfsUidSchemaStr, hdfsPathSchemaStr }; NamingEnumeration<SearchResult> results = lctx.search(baseName, matchAttrs, attrIDs); if (results.hasMore()) { String userId = null; ArrayList<Path> paths = new ArrayList<Path>(); SearchResult sr = results.next(); Attributes attrs = sr.getAttributes(); for (NamingEnumeration ne = attrs.getAll(); ne.hasMore();) { Attribute attr = (Attribute) ne.next(); if (hdfsUidSchemaStr.equalsIgnoreCase(attr.getID())) { userId = (String) attr.get(); } else if (hdfsPathSchemaStr.equalsIgnoreCase(attr.getID())) { for (NamingEnumeration e = attr.getAll(); e.hasMore();) { String pathStr = (String) e.next(); paths.add(new Path(pathStr)); } } } ldapent.init(userId, paths); if (LOG.isDebugEnabled()) LOG.debug(ldapent); return true; } LOG.info("Ip address " + userIp + " is not authorized to access the proxy server"); return false; }
From source file:ldap.Entry.java
public Entry(SearchResult result) throws InvalidNameException { this(new LdapName(result.getNameInNamespace()), result.getAttributes()); }
From source file:org.ow2.proactive.addons.ldap_query.LDAPClient.java
public String searchQueryLDAP() { NamingEnumeration results = null; ObjectMapper mapper = new ObjectMapper(); Response response;//from w w w. ja v a2 s .c o m String resultOutput = new String(); List<Map<String, String>> attributesList = new LinkedList<>(); String[] attributesToReturn = splitAttributes(allLDAPClientParameters.get(ARG_SELECTED_ATTRIBUTES)); try { ldapConnection = LDAPConnectionUtility.connect(allLDAPClientParameters.get(ARG_URL), allLDAPClientParameters.get(ARG_DN_BASE), allLDAPClientParameters.get(ARG_USERNAME), allLDAPClientParameters.get(ARG_PASSWORD)); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); if (attributesToReturn.length > 0) { controls.setReturningAttributes(attributesToReturn); } results = ldapConnection.search( getFullLdapSearchBase(allLDAPClientParameters.get(ARG_DN_BASE), allLDAPClientParameters.get(ARG_SEARCH_BASE)), allLDAPClientParameters.get(ARG_SEARCH_FILTER), controls); // Iterate through all attributes in the result of search query while (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); if (attributes != null && attributes.size() > 0) { NamingEnumeration ae = attributes.getAll(); Map<String, String> attributesMap = new HashMap<>(); while (ae.hasMore()) { Attribute attribute = (Attribute) ae.next(); attributesMap.put(attribute.getID(), attribute.get().toString()); } attributesList.add(attributesMap); } } response = new LDAPResponse("Ok", attributesList); } catch (Exception e) { response = new ErrorResponse("Error", e.toString()); } finally { if (results != null) { try { results.close(); } catch (Exception e) { e.printStackTrace(); } } if (ldapConnection != null) { try { ldapConnection.close(); } catch (Exception e) { e.printStackTrace(); } } } try { resultOutput = mapper.writeValueAsString(response); } catch (JsonProcessingException e) { e.printStackTrace(); } return resultOutput; }
From source file:org.hyperic.hq.plugin.openldap.OpenLDAPMeasurementPlugin.java
/** * @return true = monitoring is enabled * @return false = monitoring is not enabled * @exception NamingException no conection *///w w w.j a v a 2 s . c o m private boolean hasMonitoringEnabled(Metric metric) throws NamingException { NamingEnumeration enumer = null, enumerx = null, enumery = null; boolean res = false; try { String[] a = { "monitorContext" }; SearchControls cons = new SearchControls(); cons.setSearchScope(SearchControls.OBJECT_SCOPE); cons.setReturningAttributes(a); enumer = getDirContext(metric.getProperties()).search("", "(&(objectClass=*))", cons); while (enumer.hasMore() && !res) { SearchResult searchresult = (SearchResult) enumer.next(); Attributes attrs = searchresult.getAttributes(); enumerx = attrs.getIDs(); while (enumerx.hasMore()) { String id = (String) enumerx.next(); Attribute attr = attrs.get(id); res = true; } } } finally { if (enumer != null) { enumer.close(); } if (enumerx != null) { enumerx.close(); } if (enumery != null) { enumery.close(); } } log.debug("[hasMonitoringEnabled] res=" + res + " metric:" + metric); return res; }
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 w w. ja v a2 s .c om*/ 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:org.apache.cloudstack.ldap.LdapUserManager.java
private LdapUser createUser(final SearchResult result) throws NamingException { final Attributes attributes = result.getAttributes(); final String username = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getUsernameAttribute()); final String email = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getEmailAttribute()); final String firstname = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getFirstnameAttribute()); final String lastname = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getLastnameAttribute()); final String principal = result.getNameInNamespace(); String domain = principal.replace( "cn=" + LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getCommonNameAttribute()) + ",", "");/*from ww w .j a v a2 s . co m*/ domain = domain.replace("," + _ldapConfiguration.getBaseDn(), ""); domain = domain.replace("ou=", ""); return new LdapUser(username, email, firstname, lastname, principal, domain); }
From source file:org.wso2.carbon.connector.ldap.SearchEntry.java
private OMElement prepareNode(SearchResult entityResult, OMFactory factory, OMNamespace ns, String returnAttributes[]) throws NamingException { Attributes attributes = entityResult.getAttributes(); Attribute attribute;//from w ww . jav a2 s .c o m OMElement entry = factory.createOMElement(LDAPConstants.ENTRY, ns); OMElement dnattr = factory.createOMElement(LDAPConstants.DN, ns); dnattr.setText(entityResult.getNameInNamespace()); entry.addChild(dnattr); for (int i = 0; i < returnAttributes.length; i++) { attribute = attributes.get(returnAttributes[i]); if (attribute != null) { NamingEnumeration ne = null; ne = attribute.getAll(); while (ne.hasMoreElements()) { String value = (String) ne.next(); OMElement attr = factory.createOMElement(returnAttributes[i], ns); attr.setText(value); entry.addChild(attr); } } } return entry; }