List of usage examples for javax.naming.directory DirContext close
public void close() throws NamingException;
From source file:org.kitodo.production.services.data.LdapServerService.java
private boolean isPasswordCorrectForAuthWithoutTLS(Hashtable<String, String> env, User user, String password) { if (ConfigCore.getBooleanParameter(ParameterCore.LDAP_USE_SIMPLE_AUTH, false)) { env.put(Context.SECURITY_AUTHENTICATION, "none"); // TODO: test for password } else {//from w w w. j a v a 2s.co m 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 (Objects.isNull(ConfigCore.getParameter(ParameterCore.LDAP_ATTRIBUTE_TO_TEST))) { 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(ParameterCore.LDAP_ATTRIBUTE_TO_TEST)); logger.debug("ldap attributes set"); String test = (String) la.get(0); if (test.equals(ConfigCore.getParameter(ParameterCore.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
/** * create new user in LDAP-directory.// w w w.ja v a 2 s . c om * * @param user * User object * @param password * String */ public void createNewUser(User user, String password) throws NamingException, NoSuchAlgorithmException, IOException { if (!user.getLdapGroup().getLdapServer().isReadOnly()) { Hashtable<String, String> ldapEnvironment = initializeWithLdapConnectionSettings( user.getLdapGroup().getLdapServer()); LdapUser ldapUser = new LdapUser(); ldapUser.configure(user, password, getNextUidNumber(user.getLdapGroup().getLdapServer())); DirContext ctx = new InitialDirContext(ldapEnvironment); ctx.bind(buildUserDN(user), ldapUser); ctx.close(); setNextUidNumber(user.getLdapGroup().getLdapServer()); Helper.setMessage( Helper.getTranslation("ldapWritten") + " " + serviceManager.getUserService().getFullName(user)); /* * check if HomeDir exists, else create it */ logger.debug("HomeVerzeichnis pruefen"); URI homePath = getUserHomeDirectory(user); if (!new File(homePath).exists()) { logger.debug("HomeVerzeichnis existiert noch nicht"); serviceManager.getFileService().createDirectoryForUser(homePath, user.getLogin()); logger.debug("HomeVerzeichnis angelegt"); } else { logger.debug("HomeVerzeichnis existiert schon"); } } else { Helper.setMessage("ldapIsReadOnly"); } }
From source file:org.kitodo.services.data.LdapServerService.java
/** * change password of given user, needs old password for authentication. * * @param user/*from w w w . j a va2 s . c o m*/ * User object * @param inNewPassword * String * @return boolean about result of change */ public boolean changeUserPassword(User user, String inNewPassword) throws NoSuchAlgorithmException { JDKMessageDigest.MD4 digester = new JDKMessageDigest.MD4(); PasswordEncryption passwordEncryption = user.getLdapGroup().getLdapServer().getPasswordEncryptionEnum(); Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer()); if (!user.getLdapGroup().getLdapServer().isReadOnly()) { try { // encryption of password and Base64-Encoding MessageDigest md = MessageDigest.getInstance(passwordEncryption.getTitle()); md.update(inNewPassword.getBytes(StandardCharsets.UTF_8)); String encryptedPassword = new String(Base64.encodeBase64(md.digest()), StandardCharsets.UTF_8); // change attribute userPassword BasicAttribute userPassword = new BasicAttribute("userPassword", "{" + passwordEncryption + "}" + encryptedPassword); // change attribute lanmgrPassword BasicAttribute lanmgrPassword = proceedPassword("sambaLMPassword", inNewPassword, null); // change attribute ntlmPassword BasicAttribute ntlmPassword = proceedPassword("sambaNTPassword", inNewPassword, digester); BasicAttribute sambaPwdLastSet = new BasicAttribute("sambaPwdLastSet", String.valueOf(System.currentTimeMillis() / 1000L)); ModificationItem[] mods = new ModificationItem[4]; mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userPassword); mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, lanmgrPassword); mods[2] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, ntlmPassword); mods[3] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, sambaPwdLastSet); DirContext ctx = new InitialDirContext(env); ctx.modifyAttributes(buildUserDN(user), mods); // Close the context when we're done ctx.close(); return true; } catch (NamingException e) { logger.debug("Benutzeranmeldung nicht korrekt oder Passwortnderung nicht mglich", e); return false; } } return false; }
From source file:org.nuxeo.launcher.config.ConfigurationGenerator.java
/** * @param contextEnv Environment properties to build a {@link InitialDirContext} * @since 6.0//from www . ja v a 2s. c o m */ public void checkLdapConnection(Hashtable<Object, Object> contextEnv) throws NamingException { DirContext dirContext = new InitialDirContext(contextEnv); dirContext.close(); }
From source file:org.nuxeo.wizard.RouterServlet.java
public void handleUserPOST(Page currentPage, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Context ctx = Context.instance(req); ParamCollector collector = ctx.getCollector(); String refreshParam = req.getParameter("refresh"); String directoryType = collector.getConfigurationParam("nuxeo.directory.type"); if ("true".equals(refreshParam)) { currentPage.dispatchToJSP(req, resp); return;/*from www.j av a2 s .c om*/ } if ("checkNetwork".equals(refreshParam) || "checkAuth".equals(refreshParam) || "checkUserLdapParam".equals(refreshParam) || "checkGroupLdapParam".equals(refreshParam)) { try { if ("checkNetwork".equals(refreshParam)) { bindLdapConnection(collector, false); ctx.trackInfo("nuxeo.ldap.url", "info.host.found"); } else if ("checkAuth".equals(refreshParam)) { bindLdapConnection(collector, true); ctx.trackInfo("nuxeo.ldap.auth", "info.auth.success"); } else { DirContext dirContext = new InitialDirContext(getContextEnv(collector, true)); String searchScope; String searchBaseDn; String searchClass; String searchFilter; if ("checkUserLdapParam".equals(refreshParam)) { searchBaseDn = collector.getConfigurationParam("nuxeo.ldap.user.searchBaseDn"); searchScope = collector.getConfigurationParam("nuxeo.ldap.user.searchScope"); searchClass = collector.getConfigurationParam("nuxeo.ldap.user.searchClass"); searchFilter = collector.getConfigurationParam("nuxeo.ldap.user.searchFilter"); } else { searchBaseDn = collector.getConfigurationParam("nuxeo.ldap.group.searchBaseDn"); searchScope = collector.getConfigurationParam("nuxeo.ldap.group.searchScope"); searchFilter = collector.getConfigurationParam("nuxeo.ldap.group.searchFilter"); searchClass = ""; } SearchControls scts = new SearchControls(); if ("onelevel".equals(searchScope)) { scts.setSearchScope(SearchControls.ONELEVEL_SCOPE); } else { scts.setSearchScope(SearchControls.SUBTREE_SCOPE); } String filter = String.format("(&(%s)(objectClass=%s))", searchFilter.isEmpty() ? "objectClass=*" : searchFilter, searchClass.isEmpty() ? "*" : searchClass); NamingEnumeration<SearchResult> results; try { results = dirContext.search(searchBaseDn, filter, scts); if (!results.hasMore()) { ctx.trackError("nuxeo.ldap.search", "error.ldap.noresult"); } else { SearchResult result = results.next(); if (searchBaseDn.equalsIgnoreCase(result.getNameInNamespace()) && results.hasMore()) { // try not to display the root of the search // base DN result = results.next(); } ctx.trackInfo("dn", result.getNameInNamespace()); Attributes attributes = result.getAttributes(); NamingEnumeration<String> ids = attributes.getIDs(); String id; StringBuilder sb; while (ids.hasMore()) { id = ids.next(); NamingEnumeration<?> values = attributes.get(id).getAll(); sb = new StringBuilder(); while (values.hasMore()) { sb.append(values.next()).append(" , "); } ctx.trackInfo(id, sb.substring(0, sb.length() - 3)); } } } catch (NameNotFoundException e) { ctx.trackError("nuxeo.ldap.search", "error.ldap.searchBaseDn"); log.warn(e); } dirContext.close(); } } catch (AuthenticationException e) { ctx.trackError("nuxeo.ldap.auth", "error.auth.failed"); log.warn(e); } catch (NamingException e) { ctx.trackError("nuxeo.ldap.url", "error.host.not.found"); log.warn(e); } } // Form submit if (!"default".equals(directoryType) && refreshParam.isEmpty()) { // first check bind to LDAP server try { bindLdapConnection(collector, true); } catch (NamingException e) { ctx.trackError("nuxeo.ldap.auth", "error.ldap.bind.failed"); log.warn(e); } // then check mandatory fields if (collector.getConfigurationParam("nuxeo.ldap.user.searchBaseDn").isEmpty()) { ctx.trackError("nuxeo.ldap.user.searchBaseDn", "error.user.searchBaseDn.required"); } if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.rdn").isEmpty()) { ctx.trackError("nuxeo.ldap.user.mapping.rdn", "error.user.rdn.required"); } if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.username").isEmpty()) { ctx.trackError("nuxeo.ldap.user.mapping.username", "error.user.username.required"); } if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.password").isEmpty()) { ctx.trackError("nuxeo.ldap.user.mapping.password", "error.user.password.required"); } if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.firstname").isEmpty()) { ctx.trackError("nuxeo.ldap.user.mapping.firstname", "error.user.firstname.required"); } if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.lastname").isEmpty()) { ctx.trackError("nuxeo.ldap.user.mapping.lastname", "error.user.lastname.required"); } String userGroupStorage = collector.getConfigurationParam("nuxeo.user.group.storage"); if (!"userLdapOnly".equals(userGroupStorage) && !"multiUserSqlGroup".equals(userGroupStorage)) { if (collector.getConfigurationParam("nuxeo.ldap.group.searchBaseDn").isEmpty()) { ctx.trackError("nuxeo.ldap.group.searchBaseDn", "error.group.searchBaseDn.required"); } if (collector.getConfigurationParam("nuxeo.ldap.group.mapping.rdn").isEmpty()) { ctx.trackError("nuxeo.ldap.group.mapping.rdn", "error.group.rdn.required"); } if (collector.getConfigurationParam("nuxeo.ldap.group.mapping.name").isEmpty()) { ctx.trackError("nuxeo.ldap.group.mapping.name", "error.group.name.required"); } } if ("true".equals(collector.getConfigurationParam("nuxeo.user.emergency.enable"))) { if (collector.getConfigurationParam("nuxeo.user.emergency.username").isEmpty()) { ctx.trackError("nuxeo.user.emergency.username", "error.emergency.username.required"); } if (collector.getConfigurationParam("nuxeo.user.emergency.password").isEmpty()) { ctx.trackError("nuxeo.user.emergency.password", "error.emergency.password.required"); } } } if (ctx.hasErrors() || ctx.hasInfos()) { currentPage.dispatchToJSP(req, resp); } else { currentPage.next().dispatchToJSP(req, resp, true); } }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
/** * Change the password on the LDAP server. * // w w w. j a v a2 s. c om * @see org.olat.ldap.LDAPLoginManager#changePassword(org.olat.core.id.Identity, java.lang.String, org.olat.ldap.LDAPError) */ @Override public void changePassword(final Identity identity, final String pwd, final LDAPError errors) { final String uid = identity.getName(); final String ldapUserPasswordAttribute = LDAPLoginModule.getLdapUserPasswordAttribute(); try { final DirContext ctx = bindSystem(); final String dn = searchUserDN(uid, ctx); final ModificationItem[] modificationItems = new ModificationItem[1]; Attribute userPasswordAttribute; if (LDAPLoginModule.isActiveDirectory()) { // active directory need the password enquoted and unicoded (but little-endian) final String quotedPassword = "\"" + pwd + "\""; final char unicodePwd[] = quotedPassword.toCharArray(); final byte pwdArray[] = new byte[unicodePwd.length * 2]; for (int i = 0; i < unicodePwd.length; i++) { pwdArray[i * 2 + 1] = (byte) (unicodePwd[i] >>> 8); pwdArray[i * 2 + 0] = (byte) (unicodePwd[i] & 0xff); } userPasswordAttribute = new BasicAttribute(ldapUserPasswordAttribute, pwdArray); } else { userPasswordAttribute = new BasicAttribute(ldapUserPasswordAttribute, pwd); } modificationItems[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userPasswordAttribute); ctx.modifyAttributes(dn, modificationItems); ctx.close(); } catch (final NamingException e) { logError("NamingException when trying to change password with username::" + uid, e); errors.insert("Cannot change the password"); } }
From source file:org.olat.ldap.manager.LDAPLoginManagerImpl.java
/** * Change the password on the LDAP server. * @see org.olat.ldap.LDAPLoginManager#changePassword(org.olat.core.id.Identity, java.lang.String, org.olat.ldap.LDAPError) *//*from ww w . j a v a2s . co m*/ @Override public boolean changePassword(Identity identity, String pwd, LDAPError errors) { String uid = identity.getName(); String ldapUserPasswordAttribute = syncConfiguration.getLdapUserPasswordAttribute(); try { DirContext ctx = bindSystem(); String dn = ldapDao.searchUserDN(uid, ctx); ModificationItem[] modificationItems = new ModificationItem[1]; Attribute userPasswordAttribute; if (ldapLoginModule.isActiveDirectory()) { //active directory need the password enquoted and unicoded (but little-endian) String quotedPassword = "\"" + pwd + "\""; char unicodePwd[] = quotedPassword.toCharArray(); byte pwdArray[] = new byte[unicodePwd.length * 2]; for (int i = 0; i < unicodePwd.length; i++) { pwdArray[i * 2 + 1] = (byte) (unicodePwd[i] >>> 8); pwdArray[i * 2 + 0] = (byte) (unicodePwd[i] & 0xff); } userPasswordAttribute = new BasicAttribute(ldapUserPasswordAttribute, pwdArray); } else { userPasswordAttribute = new BasicAttribute(ldapUserPasswordAttribute, pwd); } modificationItems[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userPasswordAttribute); ctx.modifyAttributes(dn, modificationItems); ctx.close(); return true; } catch (NamingException e) { log.error("NamingException when trying to change password with username::" + uid, e); errors.insert("Cannot change the password"); return false; } catch (Exception e) { log.error("Unexpected exception when trying to change password with username::" + uid, e); errors.insert("Cannot change the password"); return false; } }
From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java
/** * Contacts the remote directory to determine if the password provided is valid for the * specified userId./*from w ww . j a va 2 s.c om*/ * * @param userId * the user ID to verify * @param authCredentials * the user's password to be authenticated * @return boolean * @throws NamingException * thrown if an error occurs while communicating with the remote directory */ protected boolean checkCredentials(String userId, String authCredentials) throws NamingException { DirContext context = null; boolean isValid = false; try { AuthenticationCacheEntry cacheEntry = getCachedAuthentication(userId); boolean isAuthenticationCached = false; if (cacheEntry != null) { if ((authCredentials != null) && PasswordHelper.encrypt(authCredentials).equals(cacheEntry.getEncryptedPassword())) { isAuthenticationCached = true; isValid = cacheEntry.isAuthenticationSuccessful(); } } if (!isAuthenticationCached) { // The cached authentication was expired or unavailable, so we need to perform // a live authentication against the JNDI server. context = openConnection(connectionPrincipal, connectionPassword); String userPassword; if (mode == AuthenticationMode.USER_LOOKUP) { userPassword = lookupUserPassword(userId, context); if (userPassword != null) { isValid = passwordValidator.isValidPassword(authCredentials, userPassword); } } else { // AuthenticationMode.USER_SEARCH String userDn = findUserDn(userId, context); if (userDn != null) { try { context.close(); // close the generic lookup context context = openConnection(userDn, authCredentials); isValid = true; } catch (NamingException e) { // Ignore and return false } } } // Add these results to the cache so the results will be cached for the next inquiry setCachedAuthentication( new AuthenticationCacheEntry(userId, PasswordHelper.encrypt(authCredentials), isValid)); } return isValid; } finally { try { if (context != null) context.close(); } catch (Throwable t) { } } }
From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java
/** * @see org.opentravel.schemacompiler.security.impl.AbstractAuthenticationProvider#refreshUserInfo(org.opentravel.ns.ota2.repositoryinfoext_v01_00.UserInfo) *//*from w w w. java2 s . c o m*/ @Override protected void refreshUserInfo(UserInfo userInfo) { String userId = (userInfo == null) ? null : userInfo.getUserId(); DirContext context = null; try { if (userId != null) { Long profileCacheTimeout = profileCacheTimeouts.get(userId); if ((profileCacheTimeout == null) || (System.currentTimeMillis() > profileCacheTimeout)) { context = openConnection(connectionPrincipal, connectionPassword); refreshUserInfo(userInfo, context); profileCacheTimeouts.put(userId, System.currentTimeMillis() + authenticationCacheTimeout); } } } catch (NamingException e) { log.error("Error refreshing user account: " + userId, e); } finally { try { if (context != null) context.close(); } catch (Throwable t) { } } }
From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java
/** * @see org.opentravel.schemacompiler.security.impl.AbstractAuthenticationProvider#refreshAllUsers() *//* www . j ava 2 s . c o m*/ @Override protected void refreshAllUsers() { DirContext context = null; try { for (String userId : userRegistry.keySet()) { Long profileCacheTimeout = profileCacheTimeouts.get(userId); if ((profileCacheTimeout == null) || (System.currentTimeMillis() > profileCacheTimeout)) { UserInfo userInfo = userRegistry.get(userId); if (context == null) { context = openConnection(connectionPrincipal, connectionPassword); } refreshUserInfo(userInfo, context); profileCacheTimeouts.put(userId, System.currentTimeMillis() + authenticationCacheTimeout); } } } catch (NamingException e) { log.error("Error refreshing user accounts.", e); } finally { try { if (context != null) context.close(); } catch (Throwable t) { } } }