List of usage examples for javax.naming.directory Attribute get
Object get(int ix) 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 va2 s . c o 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:de.sub.goobi.helper.ldap.Ldap.java
/** * Check if connection with login and password possible. * * @param inBenutzer//from ww w . ja v a 2 s . c o m * User object * @param inPasswort * String * @return Login correct or not */ public boolean isUserPasswordCorrect(User inBenutzer, String inPasswort) { logger.debug("start login session with ldap"); Hashtable<String, String> env = getLdapConnectionSettings(); // Start TLS if (ConfigCore.getBooleanParameter("ldap_useTLS", false)) { logger.debug("use TLS for auth"); env = new Hashtable<>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ConfigCore.getParameter("ldap_url")); 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, getUserDN(inBenutzer)); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, inPasswort); 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); } } if (ctx != null) { try { // Close LDAP connection ctx.close(); } catch (NamingException e) { logger.error(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, getUserDN(inBenutzer)); env.put(Context.SECURITY_CREDENTIALS, inPasswort); } logger.debug("ldap environment set"); try { if (logger.isDebugEnabled()) { logger.debug("start classic ldap authentification"); logger.debug("user DN is " + getUserDN(inBenutzer)); } if (ConfigCore.getParameter("ldap_AttributeToTest") == 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(getUserDN(inBenutzer)); Attribute la = attrs.get(ConfigCore.getParameter("ldap_AttributeToTest")); logger.debug("ldap attributes set"); String test = (String) la.get(0); if (test.equals(ConfigCore.getParameter("ldap_ValueOfAttribute"))) { logger.debug("ldap ok"); ctx.close(); return true; } else { logger.debug("ldap not ok"); ctx.close(); return false; } } } catch (NamingException e) { if (logger.isDebugEnabled()) { logger.debug("login not allowed for " + inBenutzer.getLogin(), e); } return false; } } }
From source file:org.kitodo.services.data.LdapServerService.java
/** * Check if connection with login and password possible. * * @param user//w w w.j a v a 2s . 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:com.evolveum.midpoint.model.common.expression.functions.BasicExpressionFunctions.java
public String determineLdapSingleAttributeValue(String dn, String attributeName, Collection<?> values) throws NamingException { if (values == null || values.isEmpty()) { return null; }// ww w. ja va2 s. co m Collection<String> stringValues = null; // Determine item type, try to convert to strings Object firstElement = values.iterator().next(); if (firstElement instanceof String) { stringValues = (Collection) values; } else if (firstElement instanceof Element) { stringValues = new ArrayList<String>(values.size()); for (Object value : values) { Element element = (Element) value; stringValues.add(element.getTextContent()); } } else { throw new IllegalArgumentException("Unexpected value type " + firstElement.getClass()); } if (stringValues.size() == 1) { return stringValues.iterator().next(); } if (StringUtils.isBlank(dn)) { throw new IllegalArgumentException( "No dn argument specified, cannot determine which of " + values.size() + " values to use"); } LdapName parsedDn = new LdapName(dn); for (int i = 0; i < parsedDn.size(); i++) { Rdn rdn = parsedDn.getRdn(i); Attributes rdnAttributes = rdn.toAttributes(); NamingEnumeration<String> rdnIDs = rdnAttributes.getIDs(); while (rdnIDs.hasMore()) { String rdnID = rdnIDs.next(); Attribute attribute = rdnAttributes.get(rdnID); if (attributeName.equals(attribute.getID())) { for (int j = 0; j < attribute.size(); j++) { Object value = attribute.get(j); if (stringValues.contains(value)) { return (String) value; } } } } } // Fallback. No values in DN. Just return the first alphabetically-wise value. return Collections.min(stringValues); }
From source file:com.emc.ecs.smart.SmartUploader.java
/** * Use JNDI to bind to DNS and resolve ALL the 'A' records for a host. * @param hostname host to resolve// w w w .j a va2 s. c om * @return the list of IP addresses for the host. */ public List<String> getIPAddresses(String hostname) throws NamingException { InitialDirContext idc; Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory"); idc = new InitialDirContext(env); List<String> ipAddresses = new ArrayList<String>(); Attributes attrs = idc.getAttributes(hostname, ADDR_ATTRIBS); Attribute attr = attrs.get(ADDR_ATTRIB); if (attr != null) { for (int i = 0; i < attr.size(); i++) { ipAddresses.add((String) attr.get(i)); } } return ipAddresses; }
From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java
/** * Performs recursive group membership lookup. * * This was how we did the lookup traditionally until we discovered 1.2.840.113556.1.4.1941. * But various people reported that it slows down the execution tremendously to the point that it is unusable, * while others seem to report that it runs faster than recursive search (http://social.technet.microsoft.com/Forums/fr-FR/f238d2b0-a1d7-48e8-8a60-542e7ccfa2e8/recursive-retrieval-of-all-ad-group-memberships-of-a-user?forum=ITCG) * * This implementation is kept for Windows 2003 that doesn't support 1.2.840.113556.1.4.1941, but it can be also * enabled for those who are seeing the performance problem. * * See JENKINS-22830//w ww . j a v a2s.co m */ private void recursiveGroupLookup(DirContext context, Attributes id, Set<GrantedAuthority> groups) throws NamingException { Stack<Attributes> q = new Stack<Attributes>(); q.push(id); while (!q.isEmpty()) { Attributes identity = q.pop(); LOGGER.finer("Looking up group of " + identity); Attribute memberOf = identity.get("memberOf"); if (memberOf == null) continue; for (int i = 0; i < memberOf.size(); i++) { try { LOGGER.log(Level.FINE, "Trying to get the CN of {0}", memberOf.get(i)); Attributes group = context.getAttributes(new LdapName(memberOf.get(i).toString()), new String[] { "CN", "memberOf" }); Attribute cn = group.get("CN"); if (cn == null) { LOGGER.fine("Failed to obtain CN of " + memberOf.get(i)); continue; } if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine(cn.get() + " is a member of " + memberOf.get(i)); if (groups.add(new GrantedAuthorityImpl(cn.get().toString()))) { q.add(group); // recursively look for groups that this group is a member of. } } catch (NameNotFoundException e) { LOGGER.fine("Failed to obtain CN of " + memberOf.get(i)); } } } }
From source file:nl.knaw.dans.common.ldap.repo.LdapMapper.java
private void setMethods(T instance, Attributes attrs) throws LdapMappingException { for (Method method : getAnnotatedSetMethods()) { String attrID = method.getAnnotation(LdapAttribute.class).id(); if (!method.getAnnotation(LdapAttribute.class).oneWayEncrypted() || !ENCRYPTION_ALGORITHM.equals(method.getAnnotation(LdapAttribute.class).encrypted())) { Attribute attr = attrs.get(attrID); Class<?> type = method.getParameterTypes()[0]; Object value = null;//from w w w .ja v a 2s . c o m Class valueTranslatorClass = method.getAnnotation(LdapAttribute.class).valueTranslator(); try { if (attr != null) { method.setAccessible(true); for (int i = 0; i < attr.size(); i++) { Object o = attr.get(i); // are not all attribute values Strings? value = getSingleValue(type, o); if (value != null) { LdapAttributeValueTranslator valueTranslator = getValueTranslator( valueTranslatorClass); value = valueTranslator.fromLdap(value); method.invoke(instance, value); } } } } catch (IllegalArgumentException e) { final String msg = "Expected " + type + " but was " + value; logger.error(msg); throw new LdapMappingException(msg, e); } catch (NamingException e) { throw new LdapMappingException(e); } catch (IllegalAccessException e) { throw new LdapMappingException(e); } catch (InvocationTargetException e) { final String msg = "Method threw exception: "; logger.error(msg, e); throw new LdapMappingException(msg, e); } catch (IndexOutOfBoundsException e) { final String msg = "Setter method has no argument: "; logger.error(msg, e); throw new LdapMappingException(msg, e); } catch (InstantiationException e) { final String msg = "Could not instantiate attribute value translator: "; logger.error(msg, e); throw new LdapMappingException(msg, e); } } } }
From source file:com.adito.activedirectory.ActiveDirectoryUserDatabase.java
private String[] getParents(Attributes attributes) throws NamingException { List<String> parents = new ArrayList<String>(); Attribute memberOfAttribute = attributes.get(MEMBER_OF_ATTIBUTE); if (memberOfAttribute != null) { final PagedResultTemplate pagedResultTemplate = configuration.getPagedResultTemplate(); for (int index = 0; index < memberOfAttribute.size(); index++) { String parentDn = (String) memberOfAttribute.get(index); if (pagedResultTemplate.isDnValid(parentDn)) { parents.add(parentDn); // valid parent so record }/*from w w w . j a v a 2s. co m*/ } } return parents.toArray(new String[parents.size()]); }
From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java
/** * Obtains the roles for the given user. * * @param username the user name to fetch user data. * @return the list of roles to which the user is associated to. * @throws NamingException LDAP error obtaining roles fro the given user *//*from www. ja v a2 s .c o m*/ protected String[] selectRolesByUsername(String username) throws NamingException, NoSuchUserException { List userRoles = new ArrayList(); InitialLdapContext ctx = createLdapInitialContext(); String rolesCtxDN = getRolesCtxDN(); // Search for any roles associated with the user if (rolesCtxDN != null) { // The attribute where user DN is stored in roles : String uidAttributeID = getUidAttributeID(); if (uidAttributeID == null) uidAttributeID = "uniquemember"; // The attribute that identifies the role name String roleAttrName = getRoleAttributeID(); if (roleAttrName == null) roleAttrName = "roles"; String userDN; if ("UID".equals(getRoleMatchingMode())) { // Use User ID to match the role userDN = username; } else if ("PRINCIPAL".equals(getRoleMatchingMode())) { // Use User ID to match the role userDN = _principalUidAttributeID + "=" + username; } else { // Default behaviour: Match the role using the User DN, not just the username : userDN = selectUserDN(username); } if (logger.isDebugEnabled()) logger.debug( "Searching Roles for user '" + userDN + "' in Uid attribute name '" + uidAttributeID + "'"); if (userDN == null) throw new NoSuchUserException(username); try { if (userDN.contains("\\")) { logger.debug("Escaping '\\' character"); userDN = userDN.replace("\\", "\\\\\\"); } NamingEnumeration answer = ctx.search(rolesCtxDN, "(&(" + uidAttributeID + "=" + userDN + "))", getSearchControls()); if (logger.isDebugEnabled()) logger.debug("Search Name: " + rolesCtxDN); if (logger.isDebugEnabled()) logger.debug("Search Filter: (&(" + uidAttributeID + "=" + userDN + "))"); if (!answer.hasMore()) logger.info("No roles found for user " + username); while (answer.hasMore()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); Attribute roles = attrs.get(roleAttrName); for (int r = 0; r < roles.size(); r++) { Object value = roles.get(r); String roleName = null; // The role attribute value is the role name roleName = value.toString(); if (roleName != null) { if (logger.isDebugEnabled()) logger.debug("Saving role '" + roleName + "' for user '" + username + "'"); userRoles.add(roleName); } } } } catch (NamingException e) { if (logger.isDebugEnabled()) logger.debug("Failed to locate roles", e); } } // Close the context to release the connection ctx.close(); return (String[]) userRoles.toArray(new String[userRoles.size()]); }
From source file:com.adito.activedirectory.ActiveDirectoryUserDatabase.java
private Collection<ActiveDirectoryGroup> getUsersGroups(Attributes attributes) throws NamingException { Attribute memberOfAttribute = attributes.get(MEMBER_OF_ATTIBUTE); if (memberOfAttribute == null) { return Collections.<ActiveDirectoryGroup>emptyList(); }// w ww. j a v a 2 s . c o m Collection<ActiveDirectoryGroup> groups = new ArrayList<ActiveDirectoryGroup>(); for (int index = 0; index < memberOfAttribute.size(); index++) { String groupDn = (String) memberOfAttribute.get(index); groups.addAll(getGroupsByDn(groupDn)); } return groups; }