List of usage examples for javax.naming.ldap LdapContext close
public void close() throws NamingException;
From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java
private void closeQuietly(LdapContext ldap) { if (ldap != null) { try {/*w w w. ja v a 2 s . c o m*/ ldap.close(); } catch (NamingException e) { LOG.error("Failed to close LDAP connection", e); } } }
From source file:org.exoplatform.services.organization.DummyLDAPServiceImpl.java
public void release(LdapContext ctx) throws NamingException { try {//from w w w. j av a 2s.c om if (ctx != null) { ctx.close(); } } catch (NamingException e) { LOG.warn("Exception occurred when tried to close context", e); } }
From source file:org.jboss.additional.testsuite.jdkall.present.elytron.sasl.OtpSaslTestCase.java
/** * Check correct user attribute values in the LDAP when using OTP algorithm. *///from ww w .j a va 2 s . c o m private void assertSequenceAndHash(Integer expectedSequence, byte[] expectedHash) throws NamingException { final Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, LDAP_URL); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system"); env.put(Context.SECURITY_CREDENTIALS, "secret"); final LdapContext ctx = new InitialLdapContext(env, null); NamingEnumeration<?> namingEnum = ctx.search("dc=wildfly,dc=org", new BasicAttributes("cn", "jduke")); if (namingEnum.hasMore()) { SearchResult sr = (SearchResult) namingEnum.next(); Attributes attrs = sr.getAttributes(); assertEquals("Unexpected sequence number in LDAP attribute", expectedSequence, new Integer(attrs.get("telephoneNumber").get().toString())); assertEquals("Unexpected hash value in LDAP attribute", Base64.getEncoder().encodeToString(expectedHash), attrs.get("title").get().toString()); } else { fail("User not found in LDAP"); } namingEnum.close(); ctx.close(); }
From source file:org.jsecurity.realm.ldap.LdapUtils.java
/** * Closes an LDAP context, logging any errors, but not throwing * an exception if there is a failure.//from w w w .j av a 2 s . c o m * * @param ctx the LDAP context to close. */ public static void closeContext(LdapContext ctx) { try { if (ctx != null) { ctx.close(); } } catch (NamingException e) { if (log.isErrorEnabled()) { log.error("Exception while closing LDAP context. ", e); } } }
From source file:org.kitodo.production.services.data.LdapServerService.java
private void closeConnections(LdapContext ctx, StartTlsResponse tls) { if (Objects.nonNull(tls)) { try {// www. ja v a 2 s . co m // Tear down TLS connection tls.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } if (Objects.nonNull(ctx)) { try { // Close LDAP connection ctx.close(); } catch (NamingException e) { logger.error(e.getMessage(), e); } } }
From source file:org.kitodo.services.data.LdapServerService.java
/** * Check if connection with login and password possible. * * @param user//from w w w . j av a 2 s. c om * User object * @param password * String * @return Login correct or not */ public boolean isUserPasswordCorrect(User user, String password) { logger.debug("start login session with ldap"); Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer()); // Start TLS if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_TLS)) { logger.debug("use TLS for auth"); env.put("java.naming.ldap.version", "3"); LdapContext ctx = null; StartTlsResponse tls = null; try { ctx = new InitialLdapContext(env, null); // Authentication must be performed over a secure channel tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest()); tls.negotiate(); // Authenticate via SASL EXTERNAL mechanism using client X.509 // certificate contained in JVM keystore ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple"); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, buildUserDN(user)); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password); ctx.reconnect(null); return true; // Perform search for privileged attributes under authenticated // context } catch (IOException e) { logger.error("TLS negotiation error:", e); return false; } catch (NamingException e) { logger.error("JNDI error:", e); return false; } finally { if (tls != null) { try { // Tear down TLS connection tls.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } if (ctx != null) { try { // Close LDAP connection ctx.close(); } catch (NamingException e) { logger.error(e.getMessage(), e); } } } } else { logger.debug("don't use TLS for auth"); if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) { env.put(Context.SECURITY_AUTHENTICATION, "none"); // TODO auf passwort testen } else { env.put(Context.SECURITY_PRINCIPAL, buildUserDN(user)); env.put(Context.SECURITY_CREDENTIALS, password); } logger.debug("ldap environment set"); try { logger.debug("start classic ldap authentication"); logger.debug("user DN is {}", buildUserDN(user)); if (ConfigCore.getParameter(Parameters.LDAP_ATTRIBUTE_TO_TEST) == null) { logger.debug("ldap attribute to test is null"); DirContext ctx = new InitialDirContext(env); ctx.close(); return true; } else { logger.debug("ldap attribute to test is not null"); DirContext ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(buildUserDN(user)); Attribute la = attrs.get(ConfigCore.getParameter(Parameters.LDAP_ATTRIBUTE_TO_TEST)); logger.debug("ldap attributes set"); String test = (String) la.get(0); if (test.equals(ConfigCore.getParameter(Parameters.LDAP_VALUE_OF_ATTRIBUTE))) { logger.debug("ldap ok"); ctx.close(); return true; } else { logger.debug("ldap not ok"); ctx.close(); return false; } } } catch (NamingException e) { logger.debug("login not allowed for {}. Exception: {}", user.getLogin(), e); return false; } } }
From source file:org.kitodo.services.data.LdapServerService.java
/** * Retrieve home directory of given user. * * @param user//from w ww . jav a 2 s .c om * User object * @return path as URI */ public URI getUserHomeDirectory(User user) { URI userFolderBasePath = URI.create("file:///" + ConfigCore.getParameter(Parameters.DIR_USERS)); if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_LOCAL_DIRECTORY)) { return userFolderBasePath.resolve(user.getLogin()); } Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer()); if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_TLS)) { env.put("java.naming.ldap.version", "3"); LdapContext ctx = null; StartTlsResponse tls = null; try { ctx = new InitialLdapContext(env, null); // Authentication must be performed over a secure channel tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest()); tls.negotiate(); ctx.reconnect(null); Attributes attrs = ctx.getAttributes(buildUserDN(user)); Attribute la = attrs.get("homeDirectory"); return URI.create((String) la.get(0)); // Perform search for privileged attributes under authenticated // context } catch (IOException e) { logger.error("TLS negotiation error:", e); return userFolderBasePath.resolve(user.getLogin()); } catch (NamingException e) { logger.error("JNDI error:", e); return userFolderBasePath.resolve(user.getLogin()); } finally { if (tls != null) { try { // Tear down TLS connection tls.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } if (ctx != null) { try { // Close LDAP connection ctx.close(); } catch (NamingException e) { logger.error(e.getMessage(), e); } } } } if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) { env.put(Context.SECURITY_AUTHENTICATION, "none"); } DirContext ctx; URI userFolderPath = null; try { ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(buildUserDN(user)); Attribute ldapAttribute = attrs.get("homeDirectory"); userFolderPath = URI.create((String) ldapAttribute.get(0)); ctx.close(); } catch (NamingException e) { logger.error(e.getMessage(), e); } if (userFolderPath != null && !userFolderPath.isAbsolute()) { if (userFolderPath.getPath().startsWith("/")) { userFolderPath = serviceManager.getFileService().deleteFirstSlashFromPath(userFolderPath); } return userFolderBasePath.resolve(userFolderPath); } else { return userFolderPath; } }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
/** * Connect to LDAP with the User-Name and Password given as parameters Configuration: LDAP URL = olatextconfig.xml (property=ldapURL) LDAP Base = olatextconfig.xml * (property=ldapBase) LDAP Attributes Map = olatextconfig.xml (property=userAttrs) * /*from w w w .ja v a2s. co m*/ * @param uid The users LDAP login name (can't be null) * @param pwd The users LDAP password (can't be null) * @return After successful bind Attributes otherwise NULL * @throws NamingException */ public Attributes bindUser(final String uid, final String pwd, final LDAPError errors) { // get user name, password and attributes final String ldapUrl = LDAPLoginModule.getLdapUrl(); final String[] userAttr = LDAPLoginModule.getUserAttrs(); if (uid == null || pwd == null) { if (isLogDebugEnabled()) { logDebug("Error when trying to bind user, missing username or password. Username::" + uid + " pwd::" + pwd); } errors.insert("Username and password must be selected"); return null; } final LdapContext ctx = bindSystem(); if (ctx == null) { errors.insert("LDAP connection error"); return null; } final String userDN = searchUserDN(uid, ctx); if (userDN == null) { logInfo("Error when trying to bind user with username::" + uid + " - user not found on LDAP server" + (LDAPLoginModule.isCacheLDAPPwdAsOLATPwdOnLogin() ? ", trying with OLAT login provider" : "")); errors.insert("Username or password incorrect"); return null; } // Ok, so far so good, user exists. Now try to fetch attributes using the // users credentials final Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapUrl); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, userDN); env.put(Context.SECURITY_CREDENTIALS, pwd); if (LDAPLoginModule.isSslEnabled()) { enableSSL(env); } try { final Control[] connectCtls = new Control[] {}; final LdapContext userBind = new InitialLdapContext(env, connectCtls); final Attributes attributes = userBind.getAttributes(userDN, userAttr); userBind.close(); return attributes; } catch (final AuthenticationException e) { logInfo("Error when trying to bind user with username::" + uid + " - invalid LDAP password"); errors.insert("Username or password incorrect"); return null; } catch (final NamingException e) { logError("NamingException when trying to get attributes after binding user with username::" + uid, e); errors.insert("Username or password incorrect"); return null; } }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
/** * Execute Batch Sync. Will update all Attributes of LDAP users in OLAt, create new users and delete users in OLAT. Can be configured in olatextconfig.xml * //w w w. j a va 2 s. c o m * @param LDAPError */ public boolean doBatchSync(final LDAPError errors) { if (WebappHelper.getNodeId() != 1) { logWarn("Sync happens only on node 1", null); return false; } // o_clusterNOK // Synchronize on class so that only one thread can read the // batchSyncIsRunning flag Only this read operation is synchronized to not // block the whole execution of the do BatchSync method. The method is used // in automatic cron scheduler job and also in GUI controllers that can't // wait for the concurrent running request to finish first, an immediate // feedback about the concurrent job is needed. -> only synchronize on the // property read. synchronized (LDAPLoginManagerImpl.class) { if (batchSyncIsRunning) { // don't run twice, skip this execution logInfo("LDAP user doBatchSync started, but another job is still running - skipping this sync"); errors.insert("BatchSync already running by concurrent process"); return false; } } coordinator.getEventBus().fireEventToListenersOf(new LDAPEvent(LDAPEvent.SYNCHING), ldapSyncLockOres); LdapContext ctx = null; boolean success = false; try { acquireSyncLock(); ctx = bindSystem(); if (ctx == null) { errors.insert("LDAP connection ERROR"); logError("Error in LDAP batch sync: LDAP connection empty", null); freeSyncLock(); success = false; return success; } final Date timeBeforeSync = new Date(); // check server capabilities // Get time before sync to have a save sync time when sync is successful final String sinceSentence = (lastSyncDate == null ? " (full sync)" : " since last sync from " + lastSyncDate); doBatchSyncDeletedUsers(ctx, sinceSentence); doBatchSyncNewAndModifiedUsers(ctx, sinceSentence, errors); // update sync time and set running flag lastSyncDate = timeBeforeSync; ctx.close(); success = true; return success; } catch (final Exception e) { errors.insert("Unknown error"); logError("Error in LDAP batch sync, unknown reason", e); success = false; return success; } finally { freeSyncLock(); if (ctx != null) { try { ctx.close(); } catch (final NamingException e) { // try but failed silently } } final LDAPEvent endEvent = new LDAPEvent(LDAPEvent.SYNCHING_ENDED); endEvent.setTimestamp(new Date()); endEvent.setSuccess(success); endEvent.setErrors(errors); coordinator.getEventBus().fireEventToListenersOf(endEvent, ldapSyncLockOres); } }
From source file:org.olat.ldap.manager.LDAPLoginManagerImpl.java
/** * /*from ww w . j a va 2s . com*/ * Connect to LDAP with the User-Name and Password given as parameters * * Configuration: LDAP URL = ldapContext.xml (property=ldapURL) LDAP Base = * ldapContext.xml (property=ldapBase) LDAP Attributes Map = * ldapContext.xml (property=userAttrs) * * * @param uid The users LDAP login name (can't be null) * @param pwd The users LDAP password (can't be null) * * @return After successful bind Attributes otherwise NULL * * @throws NamingException */ @Override public Attributes bindUser(String uid, String pwd, LDAPError errors) { // get user name, password and attributes String ldapUrl = ldapLoginModule.getLdapUrl(); String[] userAttr = syncConfiguration.getUserAttributes(); if (uid == null || pwd == null) { if (log.isDebug()) log.debug("Error when trying to bind user, missing username or password. Username::" + uid + " pwd::" + pwd); errors.insert("Username and password must be selected"); return null; } LdapContext ctx = bindSystem(); if (ctx == null) { errors.insert("LDAP connection error"); return null; } String userDN = ldapDao.searchUserDN(uid, ctx); if (userDN == null) { log.info("Error when trying to bind user with username::" + uid + " - user not found on LDAP server" + (ldapLoginModule.isCacheLDAPPwdAsOLATPwdOnLogin() ? ", trying with OLAT login provider" : "")); errors.insert("Username or password incorrect"); return null; } // Ok, so far so good, user exists. Now try to fetch attributes using the // users credentials Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapUrl); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, userDN); env.put(Context.SECURITY_CREDENTIALS, pwd); if (ldapLoginModule.getLdapConnectionTimeout() != null) { env.put(TIMEOUT_KEY, ldapLoginModule.getLdapConnectionTimeout().toString()); } if (ldapLoginModule.isSslEnabled()) { enableSSL(env); } try { Control[] connectCtls = new Control[] {}; LdapContext userBind = new InitialLdapContext(env, connectCtls); Attributes attributes = userBind.getAttributes(userDN, userAttr); userBind.close(); return attributes; } catch (AuthenticationException e) { log.info("Error when trying to bind user with username::" + uid + " - invalid LDAP password"); errors.insert("Username or password incorrect"); return null; } catch (NamingException e) { log.error("NamingException when trying to get attributes after binding user with username::" + uid, e); errors.insert("Username or password incorrect"); return null; } }