/** * Method finito. * * @throws Exception */ public void finito() throws Exception { try { if (ctx != null) ctx.close(); } catch (NamingException e) { throw e; } }
public User importLDAPUserByScreenName(long companyId, String screenName) throws Exception { long ldapServerId = PortalLDAPUtil.getLdapServerId(companyId, screenName, StringPool.BLANK); SearchResult result = (SearchResult) PortalLDAPUtil.getUser(ldapServerId, companyId, screenName, StringPool.BLANK); if (result == null) { if (_log.isWarnEnabled()) { _log.warn("No user was found in LDAP with screenName " + screenName); } return null; } LdapContext ldapContext = PortalLDAPUtil.getContext(ldapServerId, companyId); String fullUserDN = PortalLDAPUtil.getNameInNamespace(ldapServerId, companyId, result); Attributes attributes = PortalLDAPUtil.getUserAttributes(ldapServerId, companyId, ldapContext, fullUserDN); User user = importLDAPUser(ldapServerId, companyId, ldapContext, attributes, StringPool.BLANK); ldapContext.close(); return user; }
/** contact the ldap server and attempt to authenticate */ protected boolean ldapAuthenticate(String netid, String password, Context context) { if (!password.equals("")) { LdapContext ctx = null; StartTlsResponse startTLSResponse = null; // Set up environment for creating initial context Hashtable<String, String> env = new Hashtable<String, String>(); env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(javax.naming.Context.PROVIDER_URL, ldap_provider_url); try { if (useTLS) { ctx = new InitialLdapContext(env, null); // start TLS startTLSResponse = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest()); startTLSResponse.negotiate(); // perform simple client authentication ctx.addToEnvironment(javax.naming.Context.SECURITY_AUTHENTICATION, "simple"); ctx.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, netid); ctx.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS, password); ctx.addToEnvironment(javax.naming.Context.AUTHORITATIVE, "true"); ctx.addToEnvironment(javax.naming.Context.REFERRAL, "follow"); // dummy operation to check if authentication has succeeded ctx.getAttributes(""); } else if (!useTLS) { // Authenticate env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "Simple"); env.put(javax.naming.Context.SECURITY_PRINCIPAL, netid); env.put(javax.naming.Context.SECURITY_CREDENTIALS, password); env.put(javax.naming.Context.AUTHORITATIVE, "true"); env.put(javax.naming.Context.REFERRAL, "follow"); // Try to bind ctx = new InitialLdapContext(env, null); } } catch (NamingException | IOException e) { // something went wrong (like wrong password) so return false log.warn(LogManager.getHeader(context, "ldap_authentication", "type=failed_auth " + e)); return false; } finally { // Close the context when we're done try { if (startTLSResponse != null) { startTLSResponse.close(); } if (ctx != null) { ctx.close(); } } catch (NamingException | IOException e) { } } } else { return false; } return true; }
private void close(LdapContext ctx, String realm) { try { if (ctx != null) { ctx.close(); } } catch (Exception ex) { throw new RuntimeException("Could not close ldap context for realm: " + realm, ex); } }
public static void main(String[] args) { try { LdapContext ctx = ActiveDirectory.getConnection("lcevallosc", "Passw0rd"); System.out.println("Aqui tooyyy me longoneee"); ctx.close(); } catch (Exception e) { // Failed to authenticate user! e.printStackTrace(); } }
public void close() { if (initialContext != null) { try { initialContext.close(); } catch (Exception e) { // ignore LOG.log(Level.FINE, "exception while closing LDAP DIR CTX", e); } } }
public boolean closeLdap(LdapContext ldatCtx) { try { logger.debug(" start close ldap context ... "); ldatCtx.close(); logger.debug(" close ldap context success. "); return true; } catch (NamingException e) { logger.error(" close ldap context failed. ", e); return false; } }
public void importFromLDAP(long ldapServerId, long companyId) throws Exception { if (!LDAPSettingsUtil.isImportEnabled(companyId)) { return; } LdapContext ldapContext = PortalLDAPUtil.getContext(ldapServerId, companyId); if (ldapContext == null) { return; } try { Properties userMappings = LDAPSettingsUtil.getUserMappings(ldapServerId, companyId); Properties userExpandoMappings = LDAPSettingsUtil.getUserExpandoMappings(ldapServerId, companyId); Properties contactMappings = LDAPSettingsUtil.getContactMappings(ldapServerId, companyId); Properties contactExpandoMappings = LDAPSettingsUtil.getContactExpandoMappings(ldapServerId, companyId); Properties groupMappings = LDAPSettingsUtil.getGroupMappings(ldapServerId, companyId); String importMethod = PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_IMPORT_METHOD); if (importMethod.equals(_IMPORT_BY_GROUP)) { importFromLDAPByGroup( ldapServerId, companyId, ldapContext, userMappings, userExpandoMappings, contactMappings, contactExpandoMappings, groupMappings); } else if (importMethod.equals(_IMPORT_BY_USER)) { importFromLDAPByUser( ldapServerId, companyId, ldapContext, userMappings, userExpandoMappings, contactMappings, contactExpandoMappings, groupMappings); } } catch (Exception e) { _log.error("Error importing LDAP users and groups", e); } finally { if (ldapContext != null) { ldapContext.close(); } } }
// GHH 20080326 - replaced existing implementation with the same // code as used by cancel method. First try to // close the searchEnumeration, then the search context // We are very conservative when closing the enumeration // but less so when closing context, since it is safe to call close // on contexts multiple times @Override public void close() { if (searchEnumeration != null) { try { searchEnumeration.close(); } catch (Exception e) { } // catch everything, because NamingEnumeration has undefined behavior if it previously hit // an exception } if (ldapCtx != null) { try { ldapCtx.close(); } catch (NamingException ne) { LogManager.logWarning( LogConstants.CTX_CONNECTOR, LDAPPlugin.Util.gs(LDAPPlugin.Event.TEIID12003, ne.getExplanation())); } } }
/** Clean out state because of a failed authentication attempt */ private void cleanState() { username = null; if (password != null) { Arrays.fill(password, ' '); password = null; } try { if (ctx != null) { ctx.close(); } } catch (NamingException e) { // ignore } ctx = null; if (clearPass) { sharedState.remove(USERNAME_KEY); sharedState.remove(PASSWORD_KEY); } }
private Object doClose(LdapContext delegate) throws IOException, IllegalAccessException, InvocationTargetException { try { if (tls != null) { try { tls.close(); } catch (final IOException e) { throw new InvocationTargetException(e); } } } finally { try { if (delegate != null) { delegate.close(); } } catch (final NamingException e) { throw new InvocationTargetException(e); } } return null; }
protected int authenticate( long companyId, long ldapServerId, String emailAddress, String screenName, long userId, String password) throws Exception { String postfix = LDAPSettingsUtil.getPropertyPostfix(ldapServerId); LdapContext ldapContext = PortalLDAPUtil.getContext(ldapServerId, companyId); if (ldapContext == null) { return FAILURE; } try { String baseDN = PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_BASE_DN + postfix); // Process LDAP auth search filter String filter = LDAPSettingsUtil.getAuthSearchFilter( ldapServerId, companyId, emailAddress, screenName, String.valueOf(userId)); Properties userMappings = LDAPSettingsUtil.getUserMappings(ldapServerId, companyId); String userMappingsScreenName = GetterUtil.getString(userMappings.getProperty("screenName")).toLowerCase(); SearchControls searchControls = new SearchControls( SearchControls.SUBTREE_SCOPE, 1, 0, new String[] {userMappingsScreenName}, false, false); NamingEnumeration<SearchResult> enu = ldapContext.search(baseDN, filter, searchControls); if (enu.hasMoreElements()) { if (_log.isDebugEnabled()) { _log.debug("Search filter returned at least one result"); } SearchResult result = enu.nextElement(); String fullUserDN = PortalLDAPUtil.getNameInNamespace(ldapServerId, companyId, result); Attributes attributes = PortalLDAPUtil.getUserAttributes(ldapServerId, companyId, ldapContext, fullUserDN); LDAPAuthResult ldapAuthResult = null; if (PropsValues.LDAP_IMPORT_USER_PASSWORD_ENABLED) { ldapAuthResult = authenticate(ldapContext, companyId, attributes, fullUserDN, password); // Process LDAP failure codes String errorMessage = ldapAuthResult.getErrorMessage(); if (errorMessage != null) { if (errorMessage.indexOf( PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_ERROR_USER_LOCKOUT)) != -1) { throw new UserLockoutException(); } else if (errorMessage.indexOf( PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_ERROR_PASSWORD_EXPIRED)) != -1) { throw new PasswordExpiredException(); } } if (!ldapAuthResult.isAuthenticated() && PropsValues.LDAP_IMPORT_USER_PASSWORD_ENABLED) { return FAILURE; } } // Get user or create from LDAP User user = PortalLDAPImporterUtil.importLDAPUser( ldapServerId, companyId, ldapContext, attributes, password); // Process LDAP success codes if (ldapAuthResult != null) { String resultCode = ldapAuthResult.getResponseControl(); if (resultCode.equals(LDAPAuth.RESULT_PASSWORD_RESET)) { UserLocalServiceUtil.updatePasswordReset(user.getUserId(), true); } } } else { if (_log.isDebugEnabled()) { _log.debug("Search filter did not return any results"); } return DNE; } enu.close(); } catch (Exception e) { if (e instanceof PasswordExpiredException || e instanceof UserLockoutException) { throw e; } _log.error("Problem accessing LDAP server", e); return FAILURE; } finally { if (ldapContext != null) { ldapContext.close(); } } return SUCCESS; }
public User importLDAPUser( long ldapServerId, long companyId, String emailAddress, String screenName) throws Exception { LdapContext ldapContext = null; NamingEnumeration<SearchResult> enu = null; try { String postfix = LDAPSettingsUtil.getPropertyPostfix(ldapServerId); String baseDN = PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_BASE_DN + postfix); ldapContext = PortalLDAPUtil.getContext(ldapServerId, companyId); if (ldapContext == null) { throw new SystemException("Failed to bind to the LDAP server"); } String filter = PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_AUTH_SEARCH_FILTER + postfix); if (_log.isDebugEnabled()) { _log.debug("Search filter before transformation " + filter); } filter = StringUtil.replace( filter, new String[] {"@company_id@", "@email_address@", "@screen_name@"}, new String[] {String.valueOf(companyId), emailAddress, screenName}); if (_log.isDebugEnabled()) { _log.debug("Search filter after transformation " + filter); } Properties userMappings = LDAPSettingsUtil.getUserMappings(ldapServerId, companyId); String userMappingsScreenName = GetterUtil.getString(userMappings.getProperty("screenName")).toLowerCase(); SearchControls searchControls = new SearchControls( SearchControls.SUBTREE_SCOPE, 1, 0, new String[] {userMappingsScreenName}, false, false); enu = ldapContext.search(baseDN, filter, searchControls); if (enu.hasMoreElements()) { if (_log.isDebugEnabled()) { _log.debug("Search filter returned at least one result"); } Binding binding = enu.nextElement(); Attributes attributes = PortalLDAPUtil.getUserAttributes( ldapServerId, companyId, ldapContext, PortalLDAPUtil.getNameInNamespace(ldapServerId, companyId, binding)); return importLDAPUser(ldapServerId, companyId, ldapContext, attributes, StringPool.BLANK); } else { return null; } } catch (Exception e) { if (_log.isWarnEnabled()) { _log.warn("Problem accessing LDAP server " + e.getMessage()); } if (_log.isDebugEnabled()) { _log.debug(e, e); } throw new SystemException("Problem accessing LDAP server " + e.getMessage()); } finally { if (enu != null) { enu.close(); } if (ldapContext != null) { ldapContext.close(); } } }
protected int authenticate( long ldapServerId, long companyId, String emailAddress, String screenName, long userId, String password) throws Exception { LdapContext ldapContext = _portalLDAP.getContext(ldapServerId, companyId); if (ldapContext == null) { return FAILURE; } NamingEnumeration<SearchResult> enu = null; try { LDAPServerConfiguration ldapServerConfiguration = _ldapServerConfigurationProvider.getConfiguration(companyId, ldapServerId); String baseDN = ldapServerConfiguration.baseDN(); // Process LDAP auth search filter String filter = _ldapSettings.getAuthSearchFilter( ldapServerId, companyId, emailAddress, screenName, String.valueOf(userId)); Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId); String userMappingsScreenName = GetterUtil.getString(userMappings.getProperty("screenName")); userMappingsScreenName = StringUtil.toLowerCase(userMappingsScreenName); SearchControls searchControls = new SearchControls( SearchControls.SUBTREE_SCOPE, 1, 0, new String[] {userMappingsScreenName}, false, false); enu = ldapContext.search(baseDN, filter, searchControls); if (enu.hasMoreElements()) { if (_log.isDebugEnabled()) { _log.debug("Search filter returned at least one result"); } SearchResult result = enu.nextElement(); String fullUserDN = _portalLDAP.getNameInNamespace(ldapServerId, companyId, result); Attributes attributes = _portalLDAP.getUserAttributes(ldapServerId, companyId, ldapContext, fullUserDN); // Get user or create from LDAP User user = _ldapUserImporter.importUser( ldapServerId, companyId, ldapContext, attributes, password); // Authenticate LDAPAuthResult ldapAuthResult = authenticate(ldapContext, companyId, attributes, fullUserDN, password); // Process LDAP failure codes String errorMessage = ldapAuthResult.getErrorMessage(); if (errorMessage != null) { SystemLDAPConfiguration systemLDAPConfiguration = _systemLDAPConfigurationProvider.getConfiguration(companyId); int pos = errorMessage.indexOf(systemLDAPConfiguration.errorUserLockout()); if (pos != -1) { throw new UserLockoutException.LDAPLockout(fullUserDN, errorMessage); } pos = errorMessage.indexOf(systemLDAPConfiguration.errorPasswordExpired()); if (pos != -1) { throw new PasswordExpiredException(); } } if (!ldapAuthResult.isAuthenticated()) { return FAILURE; } // Process LDAP success codes String resultCode = ldapAuthResult.getResponseControl(); if (resultCode.equals(LDAPAuth.RESULT_PASSWORD_RESET)) { _userLocalService.updatePasswordReset(user.getUserId(), true); } } else { if (_log.isDebugEnabled()) { _log.debug("Search filter did not return any results"); } return DNE; } } catch (Exception e) { if (e instanceof LDAPFilterException || e instanceof PasswordExpiredException || e instanceof UserLockoutException) { throw e; } _log.error("Problem accessing LDAP server", e); return FAILURE; } finally { if (enu != null) { enu.close(); } if (ldapContext != null) { ldapContext.close(); } } return SUCCESS; }
public static void main(String[] args) throws Exception { String server = "ldap://*****:*****@tql17ad.com"; String password = "******"; boolean ssl = false; Provider prov = null; if (ssl) { prov = Security.getProvider("com.sun.net.ssl.internal.ssl.Provider"); if (prov == null) { Class moProviderClass = Class.forName("com.sun.net.ssl.internal.ssl.Provider"); Provider moProvider = (Provider) moProviderClass.newInstance(); Security.addProvider(moProvider); } } Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, server + rootCtx); env.put(Context.AUTHORITATIVE, "true"); env.put(Context.SECURITY_PRINCIPAL, admin); env.put(Context.SECURITY_CREDENTIALS, password); if (ssl) { env.put(Context.SECURITY_PROTOCOL, "ssl"); } // DirContext ctx = new InitialDirContext(env); LdapContext ctx = new InitialLdapContext(env, null); SearchControls searchCtls = new SearchControls(); // Specify the attributes to return // String returnedAtts[] = { "name", "cn" }; String returnedAtts[] = {"objectGUID", "cn", "whenChanged"}; searchCtls.setReturningAttributes(returnedAtts); // Specify the search scope searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); int pageSize = 100; byte[] cookie = null; // ***************change************ Control[] ctls = new Control[] {new PagedResultsControl(pageSize)}; ctx.setRequestControls(ctls); // ***************change************ int totalResults = 0; System.out.println("Initial context = " + ctx); do { NamingEnumeration nenum = ctx.search("", "(&(whenChanged>=19000101000000.0Z)(objectclass=group))", searchCtls); // loop through the results in each page while (nenum != null && nenum.hasMoreElements()) { SearchResult sr = (SearchResult) nenum.next(); // print out the name System.out.println("name: " + sr.getName()); // increment the counter totalResults++; } // examine the response controls cookie = parseControls(ctx.getResponseControls()); System.out.println("cookie = " + cookie + " length = " + cookie.length); // pass the cookie back to the server for the next page ctx.setRequestControls( new Control[] {new PagedResultsControl(pageSize, cookie, Control.CRITICAL)}); } while ((cookie != null) && (cookie.length != 0)); ctx.close(); System.out.println("Total entries: " + totalResults); // NamingEnumeration nenum = ctx.search("", "(objectclass=group)", // null); /* * NamingEnumeration nenum = ctx.search("", "(objectclass=group)", * searchCtls); * * int cnt = 0; for (NamingEnumeration ne = nenum; ne.hasMoreElements(); * cnt++) { SearchResult sr = (SearchResult)ne.nextElement(); * System.out.println(sr.getName()); } * * System.out.println(cnt); */ }
protected String getDNOfUser( String adminUser, String adminPassword, Context context, String netid) { // The resultant DN String resultDN; // The search scope to use (default to 0) int ldap_search_scope_value = 0; try { ldap_search_scope_value = Integer.parseInt(ldap_search_scope.trim()); } catch (NumberFormatException e) { // Log the error if it has been set but is invalid if (ldap_search_scope != null) { log.warn( LogManager.getHeader( context, "ldap_authentication", "invalid search scope: " + ldap_search_scope)); } } // Set up environment for creating initial context Hashtable<String, String> env = new Hashtable<String, String>(); env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(javax.naming.Context.PROVIDER_URL, ldap_provider_url); LdapContext ctx = null; StartTlsResponse startTLSResponse = null; try { if ((adminUser != null) && (!adminUser.trim().equals("")) && (adminPassword != null) && (!adminPassword.trim().equals(""))) { if (useTLS) { ctx = new InitialLdapContext(env, null); // start TLS startTLSResponse = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest()); startTLSResponse.negotiate(); // perform simple client authentication ctx.addToEnvironment(javax.naming.Context.SECURITY_AUTHENTICATION, "simple"); ctx.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, adminUser); ctx.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS, adminPassword); } else { // Use admin credentials for search// Authenticate env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "simple"); env.put(javax.naming.Context.SECURITY_PRINCIPAL, adminUser); env.put(javax.naming.Context.SECURITY_CREDENTIALS, adminPassword); // Create initial context ctx = new InitialLdapContext(env, null); } } else { // Use anonymous authentication env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "none"); } Attributes matchAttrs = new BasicAttributes(true); matchAttrs.put(new BasicAttribute(ldap_id_field, netid)); // look up attributes try { SearchControls ctrls = new SearchControls(); ctrls.setSearchScope(ldap_search_scope_value); String searchName = ""; if (useTLS) { searchName = ldap_search_context; } else { searchName = ldap_provider_url + ldap_search_context; } NamingEnumeration<SearchResult> answer = ctx.search(searchName, "(&({0}={1}))", new Object[] {ldap_id_field, netid}, ctrls); while (answer.hasMoreElements()) { SearchResult sr = answer.next(); if (StringUtils.isEmpty(ldap_search_context)) { resultDN = sr.getName(); } else { resultDN = (sr.getName() + "," + ldap_search_context); } String attlist[] = { ldap_email_field, ldap_givenname_field, ldap_surname_field, ldap_phone_field, ldap_group_field }; Attributes atts = sr.getAttributes(); Attribute att; if (attlist[0] != null) { att = atts.get(attlist[0]); if (att != null) { ldapEmail = (String) att.get(); } } if (attlist[1] != null) { att = atts.get(attlist[1]); if (att != null) { ldapGivenName = (String) att.get(); } } if (attlist[2] != null) { att = atts.get(attlist[2]); if (att != null) { ldapSurname = (String) att.get(); } } if (attlist[3] != null) { att = atts.get(attlist[3]); if (att != null) { ldapPhone = (String) att.get(); } } if (attlist[4] != null) { att = atts.get(attlist[4]); if (att != null) { ldapGroup = (String) att.get(); } } if (answer.hasMoreElements()) { // Oh dear - more than one match // Ambiguous user, can't continue } else { log.debug(LogManager.getHeader(context, "got DN", resultDN)); return resultDN; } } } catch (NamingException e) { // if the lookup fails go ahead and create a new record for them because the // authentication // succeeded log.warn( LogManager.getHeader(context, "ldap_attribute_lookup", "type=failed_search " + e)); } } catch (NamingException | IOException e) { log.warn(LogManager.getHeader(context, "ldap_authentication", "type=failed_auth " + e)); } finally { // Close the context when we're done try { if (startTLSResponse != null) { startTLSResponse.close(); } if (ctx != null) { ctx.close(); } } catch (NamingException | IOException e) { } } // No DN match found return null; }