List of usage examples for javax.naming.ldap LdapContext addToEnvironment
public Object addToEnvironment(String propName, Object propVal) throws NamingException;
From source file:org.apache.hadoop.security.authentication.server.LdapAuthenticationHandler.java
private void authenticateWithTlsExtension(String userDN, String password) throws AuthenticationException { LdapContext ctx = null; Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, providerUrl); try {//from ww w . ja v a2 s. c o m // Create initial context ctx = new InitialLdapContext(env, null); // Establish TLS session StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest()); if (disableHostNameVerification) { tls.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } tls.negotiate(); // Initialize security credentials & perform read operation for // verification. ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password); ctx.lookup(userDN); logger.debug("Authentication successful for {}", userDN); } catch (NamingException | IOException ex) { throw new AuthenticationException("Error validating LDAP user", ex); } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { /* Ignore. */ } } } }
From source file:org.apache.zeppelin.realm.LdapRealm.java
protected Set<String> rolesFor(PrincipalCollection principals, String userNameIn, final LdapContext ldapCtx, final LdapContextFactory ldapContextFactory, Session session) throws NamingException { final Set<String> roleNames = new HashSet<>(); final Set<String> groupNames = new HashSet<>(); final String userName; if (getUserLowerCase()) { log.debug("userLowerCase true"); userName = userNameIn.toLowerCase(); } else {/* w w w.j a v a 2 s . c o m*/ userName = userNameIn; } String userDn = getUserDnForSearch(userName); // Activate paged results int pageSize = getPagingSize(); if (log.isDebugEnabled()) { log.debug("Ldap PagingSize: " + pageSize); } int numResults = 0; byte[] cookie = null; try { ldapCtx.addToEnvironment(Context.REFERRAL, "ignore"); ldapCtx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); do { // ldapsearch -h localhost -p 33389 -D // uid=guest,ou=people,dc=hadoop,dc=apache,dc=org -w guest-password // -b dc=hadoop,dc=apache,dc=org -s sub '(objectclass=*)' NamingEnumeration<SearchResult> searchResultEnum = null; SearchControls searchControls = getGroupSearchControls(); try { if (groupSearchEnableMatchingRuleInChain) { searchResultEnum = ldapCtx.search(getGroupSearchBase(), String .format(MATCHING_RULE_IN_CHAIN_FORMAT, groupObjectClass, memberAttribute, userDn), searchControls); while (searchResultEnum != null && searchResultEnum.hasMore()) { // searchResults contains all the groups in search scope numResults++; final SearchResult group = searchResultEnum.next(); Attribute attribute = group.getAttributes().get(getGroupIdAttribute()); String groupName = attribute.get().toString(); String roleName = roleNameFor(groupName); if (roleName != null) { roleNames.add(roleName); } else { roleNames.add(groupName); } } } else { // Default group search filter String searchFilter = String.format("(objectclass=%1$s)", groupObjectClass); // If group search filter is defined in Shiro config, then use it if (groupSearchFilter != null) { searchFilter = expandTemplate(groupSearchFilter, userName); //searchFilter = String.format("%1$s", groupSearchFilter); } if (log.isDebugEnabled()) { log.debug("Group SearchBase|SearchFilter|GroupSearchScope: " + getGroupSearchBase() + "|" + searchFilter + "|" + groupSearchScope); } searchResultEnum = ldapCtx.search(getGroupSearchBase(), searchFilter, searchControls); while (searchResultEnum != null && searchResultEnum.hasMore()) { // searchResults contains all the groups in search scope numResults++; final SearchResult group = searchResultEnum.next(); addRoleIfMember(userDn, group, roleNames, groupNames, ldapContextFactory); } } } catch (PartialResultException e) { log.debug("Ignoring PartitalResultException"); } finally { if (searchResultEnum != null) { searchResultEnum.close(); } } // Re-activate paged results ldapCtx.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } while (cookie != null); } catch (SizeLimitExceededException e) { log.info("Only retrieved first " + numResults + " groups due to SizeLimitExceededException."); } catch (IOException e) { log.error("Unabled to setup paged results"); } // save role names and group names in session so that they can be // easily looked up outside of this object session.setAttribute(SUBJECT_USER_ROLES, roleNames); session.setAttribute(SUBJECT_USER_GROUPS, groupNames); if (!groupNames.isEmpty() && (principals instanceof MutablePrincipalCollection)) { ((MutablePrincipalCollection) principals).addAll(groupNames, getName()); } if (log.isDebugEnabled()) { log.debug("User RoleNames: " + userName + "::" + roleNames); } return roleNames; }
From source file:org.fao.geonet.kernel.security.ldap.LdapUserDetailsManager.java
/** * Changes the password for the current user. The username is obtained from the security * context. <p> If the old password is supplied, the update will be made by rebinding as the * user, thus modifying the password using the user's permissions. If <code>oldPassword</code> * is null, the update will be attempted using a standard read/write context supplied by the * context source. </p>/*from ww w . j av a2s . co m*/ * * @param oldPassword the old password * @param newPassword the new value of the password. */ public void changePassword(final String oldPassword, final String newPassword) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Assert.notNull(authentication, "No authentication object found in security context. Can't change current user's password!"); String username = authentication.getName(); logger.debug("Changing password for user '" + username); final DistinguishedName dn = usernameMapper.buildDn(username); final ModificationItem[] passwordChange = new ModificationItem[] { new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(passwordAttributeName, newPassword)) }; if (oldPassword == null) { template.modifyAttributes(dn, passwordChange); return; } template.executeReadWrite(new ContextExecutor() { public Object executeWithContext(DirContext dirCtx) throws NamingException { LdapContext ctx = (LdapContext) dirCtx; ctx.removeFromEnvironment("com.sun.jndi.ldap.connect.pool"); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, LdapUtils.getFullDn(dn, ctx).toString()); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, oldPassword); // TODO: reconnect doesn't appear to actually change the // credentials try { ctx.reconnect(null); } catch (javax.naming.AuthenticationException e) { throw new BadCredentialsException("Authentication for password change failed."); } ctx.modifyAttributes(dn, passwordChange); return null; } }); }
From source file:org.kitodo.production.services.data.LdapServerService.java
private boolean isPasswordCorrectForAuthWithTLS(Hashtable<String, String> env, User user, String password) { env.put("java.naming.ldap.version", "3"); LdapContext ctx = null; StartTlsResponse tls = null;//from w ww . j a v a 2 s . c o m 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 { closeConnections(ctx, tls); } }
From source file:org.kitodo.services.data.LdapServerService.java
/** * Check if connection with login and password possible. * * @param user/*from w w w . j a v a2s .com*/ * 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.ligoj.app.plugin.id.ldap.dao.UserLdapRepository.java
@Override public void setPassword(final UserOrg userLdap, final String password, final String newPassword) { log.info("Changing password for {} ...", userLdap.getId()); final ModificationItem[] passwordChange = { new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(PASSWORD_ATTRIBUTE, digest(newPassword))) }; // Unlock account when the user is locked by ppolicy set(userLdap, PWD_ACCOUNT_LOCKED_ATTRIBUTE, null); // Authenticate the user is needed before changing the password. template.executeReadWrite(new ContextExecutor<>() { @Override/*from w w w . j av a2 s . c o m*/ public Object executeWithContext(final DirContext dirCtx) throws NamingException { LdapContext ctx = (LdapContext) dirCtx; ctx.removeFromEnvironment(LDAP_CONNECT_POOL); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userLdap.getDn()); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password == null ? getTmpPassword(userLdap) : password); try { ctx.reconnect(null); ctx.modifyAttributes(userLdap.getDn(), passwordChange); } catch (final AuthenticationException e) { log.info("Authentication failed for {}: {}", userLdap.getId(), e.getMessage()); throw new ValidationJsonException("password", "login"); } catch (final InvalidAttributeValueException e) { log.info("Password change failed due to: {}", e.getMessage()); throw new ValidationJsonException("password", "password-policy"); } return null; } }); }
From source file:org.springframework.security.ldap.userdetails.LdapUserDetailsManager.java
private void changePasswordUsingAttributeModification(DistinguishedName userDn, String oldPassword, String newPassword) {//from www . j a v a 2 s. c om final ModificationItem[] passwordChange = new ModificationItem[] { new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(passwordAttributeName, newPassword)) }; if (oldPassword == null) { template.modifyAttributes(userDn, passwordChange); return; } template.executeReadWrite(dirCtx -> { LdapContext ctx = (LdapContext) dirCtx; ctx.removeFromEnvironment("com.sun.jndi.ldap.connect.pool"); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, LdapUtils.getFullDn(userDn, ctx).toString()); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, oldPassword); // TODO: reconnect doesn't appear to actually change the credentials try { ctx.reconnect(null); } catch (javax.naming.AuthenticationException e) { throw new BadCredentialsException("Authentication for password change failed."); } ctx.modifyAttributes(userDn, passwordChange); return null; }); }