List of usage examples for javax.naming.directory SearchControls SearchControls
public SearchControls()
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static boolean isMailUsed(String mail) { boolean registered = false; NamingEnumeration results = null; DirContext ctx = null;//w w w. j av a 2 s. co m try { ctx = getContext(); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); ResourceBundle rb = ResourceBundle.getBundle("ldap"); results = ctx.search(rb.getString("peopleRoot"), "(mail=" + mail + ")", controls); if (results.hasMore()) { registered = true; } } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { registered = true; } 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 registered; }
From source file:org.archone.ad.authentication.ShoadRealm.java
private String getUserDn(String username) throws javax.naming.NamingException { SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); DirContext dirContext = contextSource.getReadOnlyContext(); NamingEnumeration<SearchResult> searchResults = dirContext.search("", adConfiguration.getUserDnSearchFilter(), new String[] { username }, controls); SearchResult sr = searchResults.next(); if (sr == null || searchResults.hasMore()) { throw new AuthenticationException(); }//from w w w. j a v a 2 s . c om return sr.getNameInNamespace(); }
From source file:io.apiman.gateway.engine.policies.BasicAuthLDAPTest.java
@Test @Ignore//from ww w. j a va 2 s . c om public void testLdap() throws Exception { DirContext ctx = createContext(); Assert.assertNotNull(ctx); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> result = ctx.search("o=apiman", "(ObjectClass=*)", controls); System.out.println(" ==== Search Results ===="); while (result.hasMore()) { SearchResult entry = result.next(); System.out.println(" ===> " + entry.getName()); } }
From source file:org.wso2.carbon.appfactory.userstore.OTAppFactoryUserStore.java
@Override public String[] doListUsers(String filter, int maxItemLimit) throws UserStoreException { String[] userNames = new String[0]; if (maxItemLimit == 0) { return userNames; }/*from ww w. j a v a 2s. co m*/ int givenMax = Integer .parseInt(realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST)); if (maxItemLimit < 0 || maxItemLimit > givenMax) { maxItemLimit = givenMax; } SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setCountLimit(maxItemLimit); if (filter.contains("?") || filter.contains("**")) { throw new UserStoreException( "Invalid character sequence entered for user serch. Please enter valid sequence."); } StringBuffer searchFilter = null; searchFilter = new StringBuffer(realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER)); String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE); StringBuffer buff = new StringBuffer(); buff.append("(&").append(searchFilter).append("(").append(userNameProperty).append("=").append(filter) .append("))"); String serviceNameAttribute = "sn"; String mailAttribute = "mail"; String returnedAtts[] = { userNameProperty, serviceNameAttribute, mailAttribute }; searchCtls.setReturningAttributes(returnedAtts); DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; String[] allUserNames = null; try { dirContext = connectionSource.getContext(); answer = dirContext.search(searchBase, buff.toString(), searchCtls); List<String> list = new ArrayList<String>(); int i = 0; while (answer.hasMoreElements() && i < maxItemLimit) { SearchResult sr = (SearchResult) answer.next(); if (sr.getAttributes() != null) { Attribute attr = sr.getAttributes().get(mailAttribute); /* * If this is a service principle, just ignore and iterate rest of the array. * The entity is a service if value of surname is Service */ Attribute attrSurname = sr.getAttributes().get(serviceNameAttribute); if (attrSurname != null) { String serviceName = (String) attrSurname.get(); if (serviceName != null && serviceName.equals(LDAPConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE)) { continue; } } if (attr != null) { String name = (String) attr.get(); //append the domain if exist String domain = userRealm.getRealmConfiguration() .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME); if (domain != null) { domain = domain + "/"; name = domain + name; } list.add(name); i++; } } } userNames = list.toArray(new String[list.size()]); //get secondary user lists UserStoreManager secUserManager = this.getSecondaryUserStoreManager(); if (secUserManager != null) { String[] secUserNames = secUserManager.listUsers(filter, maxItemLimit); allUserNames = UserCoreUtil.combineArrays(userNames, secUserNames); } else { allUserNames = userNames; } Arrays.sort(allUserNames); } catch (NamingException e) { log.error(e.getMessage(), e); throw new UserStoreException(e.getMessage(), e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return allUserNames; }
From source file:org.wso2.carbon.identity.account.suspension.notification.task.ldap.LDAPNotificationReceiversRetrieval.java
@Override public List<NotificationReceiver> getNotificationReceivers(long lookupMin, long lookupMax, long delayForSuspension, String tenantDomain) throws AccountSuspensionNotificationException { List<NotificationReceiver> users = new ArrayList<NotificationReceiver>(); if (realmConfiguration != null) { String ldapSearchBase = realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); RealmService realmService = NotificationTaskDataHolder.getInstance().getRealmService(); try {// ww w . j a va2s .c om ClaimManager claimManager = (ClaimManager) realmService .getTenantUserRealm(IdentityTenantUtil.getTenantId(tenantDomain)).getClaimManager(); String userStoreDomain = realmConfiguration .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME); if (StringUtils.isBlank(userStoreDomain)) { userStoreDomain = IdentityUtil.getPrimaryDomainName(); } String usernameMapAttribute = claimManager.getAttributeName(userStoreDomain, NotificationConstants.USERNAME_CLAIM); String firstNameMapAttribute = claimManager.getAttributeName(userStoreDomain, NotificationConstants.FIRST_NAME_CLAIM); String emailMapAttribute = claimManager.getAttributeName(userStoreDomain, NotificationConstants.EMAIL_CLAIM); String lastLoginTimeAttribute = claimManager.getAttributeName(userStoreDomain, NotificationConstants.LAST_LOGIN_TIME); if (log.isDebugEnabled()) { log.debug( "Retrieving ldap user list for lookupMin: " + lookupMin + " - lookupMax: " + lookupMax); } LDAPConnectionContext ldapConnectionContext = new LDAPConnectionContext(realmConfiguration); DirContext ctx = ldapConnectionContext.getContext(); //carLicense is the mapped LDAP attribute for LastLoginTime claim String searchFilter = "(&(" + lastLoginTimeAttribute + ">=" + lookupMin + ")(" + lastLoginTimeAttribute + "<=" + lookupMax + "))"; SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase, searchFilter, searchControls); if (log.isDebugEnabled()) { log.debug("LDAP user list retrieved."); } while (results.hasMoreElements()) { SearchResult result = results.nextElement(); NotificationReceiver receiver = new NotificationReceiver(); receiver.setEmail((String) result.getAttributes().get(emailMapAttribute).get()); receiver.setUsername((String) result.getAttributes().get(usernameMapAttribute).get()); receiver.setFirstName((String) result.getAttributes().get(firstNameMapAttribute).get()); receiver.setUserStoreDomain(userStoreDomain); long lastLoginTime = Long .parseLong(result.getAttributes().get(lastLoginTimeAttribute).get().toString()); long expireDate = lastLoginTime + TimeUnit.DAYS.toMillis(delayForSuspension); receiver.setExpireDate(new SimpleDateFormat("dd-MM-yyyy").format(new Date(expireDate))); if (log.isDebugEnabled()) { log.debug("Expire date was set to: " + receiver.getExpireDate()); } users.add(receiver); } } catch (NamingException e) { throw new AccountSuspensionNotificationException("Failed to filter users from LDAP user store.", e); } catch (UserStoreException e) { throw new AccountSuspensionNotificationException("Failed to load LDAP connection context.", e); } catch (org.wso2.carbon.user.api.UserStoreException e) { throw new AccountSuspensionNotificationException( "Error occurred while getting tenant user realm for " + "tenant:" + tenantDomain, e); } } return users; }
From source file:org.openadaptor.auxil.connector.jndi.JNDISearch.java
/** * Default constructor for a JNDI Search. * <p>/* ww w. j a v a2 s . co m*/ * Will default to having a default SearchControls instance - as returned by new SearchControls() Will also default to * use the first value of multi-valued attributes. */ public JNDISearch() { // No-arg constructor for beans searchControls = new SearchControls();// Start with defaults. _treatMultiValuedAttributesAsArray = false; // Todo: Review this default. }
From source file:fr.iphc.grid.jobmonitor.CeList.java
static public ArrayList<URL> AvailableLdapCe() throws Exception { ArrayList<URL> CeList = new ArrayList<URL>(); 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://cclcgtopbdii01.in2p3.fr:2170"); env.put("java.naming.ldap.attributes.binary", "objectSID"); try {/* ww w. jav a 2s . co m*/ // Create initial context DirContext ctx = new InitialDirContext(env); SearchControls contraints = new SearchControls(); contraints.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] attributIDs = { "GlueCEUniqueID" }; contraints.setReturningAttributes(attributIDs); String BASE_SEARCH = "Mds-Vo-name=local,o=grid"; String filter = "(&(objectClass=GlueCE)(GlueCEImplementationName=CREAM)(GlueCEAccessControlBaseRule=VO:biomed))"; NamingEnumeration<SearchResult> answer = ctx.search(BASE_SEARCH, filter, contraints); // int index = 0; Random rand = new Random(); while (answer.hasMore()) { // index++; SearchResult result = answer.next(); // Attributes attrs = result.getAttributes(); // NamingEnumeration f = attrs.getAll(); // Attribute attr = (Attribute) f.next(); String line = "cream://" + result.getAttributes().get("GlueCEUniqueID").get() + "?delegationId=" + rand.nextLong(); URL serviceURL = URLFactory.createURL(line); CeList.add(serviceURL); } // Close the context when we're done ctx.close(); } catch (Exception e) { e.printStackTrace(); } ; return CeList; }
From source file:com.photon.phresco.ldap.impl.LDAPManagerImpl.java
private User getUser(Credentials credentials, DirContext ctx) throws PhrescoException { if (isDebugEnabled) { S_LOGGER.debug("Entering Method LDAPManagerImpl.getUserInfo(String userName, DirContext ctx)"); }/* ww w . j a va2s .com*/ User user = new User(); try { String userName = credentials.getUsername(); SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] attrIDs = { "*" }; constraints.setReturningAttributes(attrIDs); NamingEnumeration<SearchResult> ne = ctx.search(ldapConfig.getLdapBaseDn(), ldapConfig.getLdapLoginAttribute() + Constants.STR_EQUALS + userName, constraints); if (ne.hasMore()) { Attributes attrs = ne.next().getAttributes(); user.setName(userName); // userInfo.setCredentials(credentials); user.setDisplayName(getDisplayName(attrs)); user.setEmail(getMailId(attrs)); user.setPhrescoEnabled(isPhrescoEnabled(attrs)); // userInfo.setCustomerNames(getCustomerNames(attrs)); } } catch (Exception e) { throw new PhrescoException(e); } return user; }
From source file:org.jasig.portal.security.provider.SimpleLdapSecurityContext.java
/** * Authenticates the user.//from w ww .j av a2 s. c o m */ 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: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; }