List of usage examples for javax.naming.directory DirContext search
public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException;
From source file:org.apache.syncope.fit.core.reference.GroupITCase.java
@Test public void issueSYNCOPE632() { GroupTO groupTO = null;/* w w w.j a v a 2s .c o m*/ try { // 1. create new LDAP resource having ConnObjectKey mapped to a derived attribute ResourceTO newLDAP = resourceService.read(RESOURCE_NAME_LDAP); newLDAP.setKey("new-ldap"); newLDAP.setPropagationPrimary(true); MappingTO mapping = newLDAP.getProvision(AnyTypeKind.GROUP.name()).getMapping(); MappingItemTO connObjectKey = mapping.getConnObjectKeyItem(); connObjectKey.setIntMappingType(IntMappingType.GroupDerivedSchema); connObjectKey.setIntAttrName("displayProperty"); mapping.setConnObjectKeyItem(connObjectKey); mapping.setConnObjectLink("'cn=' + displayProperty + ',ou=groups,o=isp'"); MappingItemTO description = new MappingItemTO(); description.setIntMappingType(IntMappingType.GroupKey); description.setExtAttrName("description"); description.setPurpose(MappingPurpose.BOTH); mapping.add(description); newLDAP = createResource(newLDAP); assertNotNull(newLDAP); // 2. create a group and give the resource created above groupTO = getSampleTO("lastGroup" + getUUIDString()); groupTO.getPlainAttrs().add(attrTO("icon", "anIcon")); groupTO.getPlainAttrs().add(attrTO("show", "true")); groupTO.getDerAttrs().add(attrTO("displayProperty", null)); groupTO.getResources().clear(); groupTO.getResources().add("new-ldap"); groupTO = createGroup(groupTO); assertNotNull(groupTO); // 3. update the group GroupMod groupMod = new GroupMod(); groupMod.setKey(groupTO.getKey()); groupMod.getPlainAttrsToRemove().add("icon"); groupMod.getPlainAttrsToUpdate().add(attrMod("icon", "anotherIcon")); groupTO = updateGroup(groupMod); assertNotNull(groupTO); // 4. check that a single group exists in LDAP for the group created and updated above int entries = 0; DirContext ctx = null; try { ctx = getLdapResourceDirContext(null, null); SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(new String[] { "*", "+" }); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> result = ctx.search("ou=groups,o=isp", "(description=" + groupTO.getKey() + ")", ctls); while (result.hasMore()) { result.next(); entries++; } } catch (Exception e) { // ignore } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { // ignore } } } assertEquals(1, entries); } finally { if (groupTO != null) { groupService.delete(groupTO.getKey()); } resourceService.delete("new-ldap"); } }
From source file:org.apache.syncope.fit.core.reference.RoleITCase.java
@Test public void issueSYNCOPE632() { RoleTO roleTO = null;/*w w w. j a v a2 s .c o m*/ try { // 1. create new LDAP resource having account id mapped to a derived attribute ResourceTO newLDAP = resourceService.read(RESOURCE_NAME_LDAP); newLDAP.setKey("new-ldap"); newLDAP.setPropagationPrimary(true); MappingItemTO accountId = newLDAP.getRmapping().getAccountIdItem(); accountId.setIntMappingType(IntMappingType.RoleDerivedSchema); accountId.setIntAttrName("displayProperty"); newLDAP.getRmapping().setAccountIdItem(accountId); newLDAP.getRmapping().setAccountLink("'cn=' + displayProperty + ',ou=groups,o=isp'"); MappingItemTO description = new MappingItemTO(); description.setIntMappingType(IntMappingType.RoleId); description.setExtAttrName("description"); description.setPurpose(MappingPurpose.BOTH); newLDAP.getRmapping().addItem(description); newLDAP = createResource(newLDAP); assertNotNull(newLDAP); // 2. create a role and give the resource created above roleTO = buildRoleTO("lastRole"); roleTO.getRPlainAttrTemplates().add("icon"); roleTO.getPlainAttrs().add(attrTO("icon", "anIcon")); roleTO.getRPlainAttrTemplates().add("show"); roleTO.getPlainAttrs().add(attrTO("show", "true")); roleTO.getRDerAttrTemplates().add("displayProperty"); roleTO.getDerAttrs().add(attrTO("displayProperty", null)); roleTO.getResources().clear(); roleTO.getResources().add("new-ldap"); roleTO = createRole(roleTO); assertNotNull(roleTO); // 3. update the role RoleMod roleMod = new RoleMod(); roleMod.setKey(roleTO.getKey()); roleMod.getPlainAttrsToRemove().add("icon"); roleMod.getPlainAttrsToUpdate().add(attrMod("icon", "anotherIcon")); roleTO = updateRole(roleMod); assertNotNull(roleTO); // 4. check that a single group exists in LDAP for the role created and updated above int entries = 0; DirContext ctx = null; try { ctx = getLdapResourceDirContext(null, null); SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(new String[] { "*", "+" }); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> result = ctx.search("ou=groups,o=isp", "(description=" + roleTO.getKey() + ")", ctls); while (result.hasMore()) { result.next(); entries++; } } catch (Exception e) { // ignore } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { // ignore } } } assertEquals(1, entries); } finally { if (roleTO != null) { roleService.delete(roleTO.getKey()); } resourceService.delete("new-ldap"); } }
From source file:org.apereo.portal.groups.ldap.LDAPGroupStore.java
public EntityIdentifier[] searchForEntities(String query, int method, Class type) throws GroupsException { if (type != group && type != iperson) return new EntityIdentifier[0]; // Guarantee that LDAP injection is prevented by replacing LDAP special characters // with escaped versions of the character query = LdapEncoder.filterEncode(query); ArrayList ids = new ArrayList(); switch (method) { case STARTS_WITH: query = query + "*"; break;/*from w w w .j a v a2s.c o m*/ case ENDS_WITH: query = "*" + query; break; case CONTAINS: query = "*" + query + "*"; break; } query = namefield + "=" + query; DirContext context = getConnection(); NamingEnumeration userlist = null; SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(new String[] { keyfield }); try { userlist = context.search(usercontext, query, sc); ArrayList keys = new ArrayList(); processLdapResults(userlist, keys); String[] k = (String[]) keys.toArray(new String[0]); for (int i = 0; i < k.length; i++) { ids.add(new EntityIdentifier(k[i], iperson)); } return (EntityIdentifier[]) ids.toArray(new EntityIdentifier[0]); } catch (NamingException nex) { throw new GroupsException("LDAPGroupStore: Unable to perform filter " + query, nex); } }
From source file:org.ballerinalang.auth.ldap.util.LdapUtils.java
/** * Searches the corresponding name for a given username from LDAP. * * @param userName Given username * @param searchBase LDAP search base * @param searchFilter LDAP search filter * @param dirContext Directory naming context * @return Associated name for the given username * @throws UserStoreException if there is any exception occurs during the process * @throws NamingException if there is any exception occurs during the process *//* w w w . ja v a 2s. c o m*/ public static String getNameInSpaceForUserName(String userName, String searchBase, String searchFilter, DirContext dirContext) throws UserStoreException, NamingException { if (userName == null) { throw new UserStoreException("userName value is null."); } String userDN = null; NamingEnumeration<SearchResult> answer = null; try { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] searchBases = searchBase.split("#"); for (String base : searchBases) { answer = dirContext.search(escapeDNForSearch(base), searchFilter, searchCtls); if (!(answer.hasMore())) { continue; } SearchResult userObj = answer.next(); if (userObj != null) { //no need to decode since , if decoded the whole string, can't be encoded again //eg CN=Hello\,Ok=test\,test, OU=Industry userDN = userObj.getNameInNamespace(); break; } } if (LOG.isDebugEnabled()) { LOG.debug("Name in space for " + userName + " is " + userDN); } } finally { LdapUtils.closeNamingEnumeration(answer); } return userDN; }
From source file:org.ballerinalang.stdlib.ldap.nativeimpl.GetLdapScopesOfUser.java
private static List<String> getListOfNames(List<String> searchBases, String searchFilter, SearchControls searchCtls, String property, DirContext ldapConnectionContext) throws NamingException { if (LOG.isDebugEnabled()) { LOG.debug("Result for searchBase: " + searchBases + " searchFilter: " + searchFilter + " property:" + property + " appendDN: false"); }//from w w w. j a va 2 s . co m List<String> names = new ArrayList<>(); NamingEnumeration<SearchResult> answer = null; try { // handle multiple search bases for (String searchBase : searchBases) { answer = ldapConnectionContext.search(LdapUtils.escapeDNForSearch(searchBase), searchFilter, searchCtls); while (answer.hasMoreElements()) { SearchResult searchResult = answer.next(); if (searchResult.getAttributes() == null) { continue; } Attribute attr = searchResult.getAttributes().get(property); if (attr == null) { continue; } for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) { String name = (String) vals.nextElement(); if (LOG.isDebugEnabled()) { LOG.debug("Found user: " + name); } names.add(name); } } if (LOG.isDebugEnabled()) { for (String name : names) { LOG.debug("Result : " + name); } } } } finally { LdapUtils.closeNamingEnumeration(answer); } return names; }
From source file:org.beangle.security.ldap.connect.SimpleLdapUserStore.java
public String getUserDN(String uid) { DirContext ctx = getContext(); if (ctx == null) return null; String result = null;/*from w w w. j av a2 s . c om*/ String condition = StrUtils.concat(uidName, "=", uid); try { String attrList[] = { uidName }; SearchControls constraints = new SearchControls(); constraints.setSearchScope(2); constraints.setReturningAttributes(attrList); NamingEnumeration<SearchResult> results = ctx.search(base, condition, constraints); if (results.hasMore()) { SearchResult si = results.next(); result = StrUtils.concat(si.getName(), ",", base); } results.close(); results = null; } catch (Throwable e) { logger.error("Ldap search error,uid=" + uid, e); } return result; }
From source file:org.codehaus.plexus.redback.authentication.ldap.LdapBindAuthenticator.java
public AuthenticationResult authenticate(AuthenticationDataSource s) throws AuthenticationException { PasswordBasedAuthenticationDataSource source = (PasswordBasedAuthenticationDataSource) s; if (!config.getBoolean("ldap.bind.authenticator.enabled") || (!config.getBoolean("ldap.bind.authenticator.allowEmptyPasswords", false) && StringUtils.isEmpty(source.getPassword()))) { return new AuthenticationResult(false, source.getPrincipal(), null); }/*from w w w .ja v a 2 s. c o m*/ SearchControls ctls = new SearchControls(); ctls.setCountLimit(1); ctls.setDerefLinkFlag(true); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "(&(objectClass=" + mapper.getUserObjectClass() + ")" + (mapper.getUserFilter() != null ? mapper.getUserFilter() : "") + "(" + mapper.getUserIdAttribute() + "=" + source.getPrincipal() + "))"; log.info("Searching for users with filter: \'{}\'" + " from base dn: {}", filter, mapper.getUserBaseDn()); LdapConnection ldapConnection = getLdapConnection(); LdapConnection authLdapConnection = null; NamingEnumeration<SearchResult> results = null; try { // check the cache for user's userDn in the ldap server String userDn = ldapCacheService.getLdapUserDn(source.getPrincipal()); if (userDn == null) { log.debug("userDn for user {} not found in cache. Retrieving from ldap server..", source.getPrincipal()); DirContext context = ldapConnection.getDirContext(); results = context.search(mapper.getUserBaseDn(), filter, ctls); log.info("Found user?: {}", results.hasMoreElements()); if (results.hasMoreElements()) { SearchResult result = results.nextElement(); userDn = result.getNameInNamespace(); log.debug("Adding userDn {} for user {} to the cache..", userDn, source.getPrincipal()); // REDBACK-289/MRM-1488 cache the ldap user's userDn to lessen calls to ldap server ldapCacheService.addLdapUserDn(source.getPrincipal(), userDn); } else { return new AuthenticationResult(false, source.getPrincipal(), null); } } log.info("Attempting Authenication: + {}", userDn); authLdapConnection = connectionFactory.getConnection(userDn, source.getPassword()); return new AuthenticationResult(true, source.getPrincipal(), null); } catch (LdapException e) { return new AuthenticationResult(false, source.getPrincipal(), e); } catch (NamingException e) { return new AuthenticationResult(false, source.getPrincipal(), e); } finally { closeNamingEnumeration(results); closeLdapConnection(ldapConnection); if (authLdapConnection != null) { closeLdapConnection(authLdapConnection); } } }
From source file:org.infoscoop.account.ldap.LDAPAccountManager.java
public IAccount getUser(String uid) throws NamingException { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration searchResultEnum; Map filters = new HashMap(); String uidAttrName = "uid"; if (this.propAttrMap.containsKey("user_id")) { try {//from w w w .ja va 2s .c om uidAttrName = (String) this.propAttrMap.get("user_id"); } catch (Exception ex) { //ignore } } if (uid != null && !"".equals(uid)) filters.put(uidAttrName, uid); DirContext context = null; try { context = this.initContext(); searchResultEnum = context.search(userBase, buildFilterByUid(filters), searchControls); //roop of retrieval result while (searchResultEnum.hasMore()) { SearchResult searchResult = (SearchResult) searchResultEnum.next(); String dn = searchResult.getName() + "," + userBase; LDAPAccount user = createLDAPUser(dn, searchResult.getAttributes()); setGroup(context, user); return user; } return null; } finally { if (context != null) context.close(); } }
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())); }/* w w w. jav a 2s .com*/ 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.infoscoop.account.ldap.LDAPAccountManager.java
private List searchFromUsers(DirContext context, Map filters) throws NamingException { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration searchResultEnum; String filter = buildFilter(filters); if (log.isInfoEnabled()) log.info("Search User from " + userBase + " by " + filter); searchResultEnum = context.search(userBase, filter, searchControls); //roop of retrieval result List users = new ArrayList(); while (searchResultEnum.hasMore()) { SearchResult searchResult = (SearchResult) searchResultEnum.next(); String dn = searchResult.getName() + "," + userBase; LDAPAccount user = createLDAPUser(dn, searchResult.getAttributes()); users.add(user);/*from www . j a va2s .c o m*/ } return users; }