List of usage examples for javax.naming.directory Attribute get
Object get() throws NamingException;
From source file:org.jenkinsci.plugins.reverse_proxy_auth.ReverseProxySecurityRealm.java
/** * Infer the root DN.//from w w w . j a v a 2s.com * * @return null if not found. */ private String inferRootDN(String server) { try { Hashtable<String, String> props = new Hashtable<String, String>(); if (managerDN != null) { props.put(Context.SECURITY_PRINCIPAL, managerDN); props.put(Context.SECURITY_CREDENTIALS, getManagerPassword()); } props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, toProviderUrl(fixNull(getServerUrl()), "")); DirContext ctx = new InitialDirContext(props); Attributes atts = ctx.getAttributes(""); Attribute a = atts.get("defaultNamingContext"); if (a != null && a.get() != null) { // this entry is available on Active Directory. See http://msdn2.microsoft.com/en-us/library/ms684291(VS.85).aspx return a.get().toString(); } a = atts.get("namingcontexts"); if (a == null) { LOGGER.warning("namingcontexts attribute not found in root DSE of " + server); return null; } return a.get().toString(); } catch (NamingException e) { LOGGER.log(Level.WARNING, "Failed to connect to LDAP to infer Root DN for " + server, e); return null; } }
From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java
private boolean bindSearchX(String username, String password, Hashtable<String, String> env, boolean bind) throws AuthenticationException, NamingException { env.put(Context.SECURITY_PRINCIPAL, ldapSecurityPrincipal); env.put(Context.SECURITY_CREDENTIALS, ldapSecurityCredentials); DirContext ctx = null;// w w w .j ava2 s. c o m try { ctx = new InitialDirContext(env); } catch (NamingException ne) { log.error("Failed to bind as: {}", ldapSecurityPrincipal); } // ensure we have the userPassword attribute at a minimum String[] attributeList = new String[] { "userPassword" }; SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(attributeList); sc.setDerefLinkFlag(true); sc.setReturningObjFlag(false); sc.setTimeLimit(5000); String filter = "(" + filterPrefix + idAttr + "=" + username + filterSuffix + ")"; // Do the search NamingEnumeration<SearchResult> results = ctx.search(baseDn, filter, sc); if (!results.hasMore()) { log.warn("no valid user found."); return false; } SearchResult result = results.next(); log.debug("authenticating user: {}", result.getNameInNamespace()); if (bind) { // setup user context for binding Hashtable<String, String> userEnv = new Hashtable<String, String>(); userEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); userEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); userEnv.put(Context.PROVIDER_URL, baseUrl); userEnv.put(Context.SECURITY_PRINCIPAL, result.getNameInNamespace()); userEnv.put(Context.SECURITY_CREDENTIALS, password); try { new InitialDirContext(userEnv); } catch (NamingException ne) { log.error("failed to authenticate user: " + result.getNameInNamespace()); throw ne; } } else { // get userPassword attribute Attribute up = result.getAttributes().get("userPassword"); if (up == null) { log.error("unable to read userPassword attribute for: {}", result.getNameInNamespace()); return false; } byte[] userPasswordBytes = (byte[]) up.get(); String userPassword = new String(userPasswordBytes); // compare passwords - also handles encodings if (!passwordsMatch(password, userPassword)) { return false; } } return true; }
From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java
public List<String> getGroups(String username, DirContext context) throws MappingException { List<String> userGroups = new ArrayList<String>(); NamingEnumeration<SearchResult> namingEnumeration = null; try {//from w ww .j a v a2 s . c o m SearchControls searchControls = new SearchControls(); searchControls.setDerefLinkFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String groupEntry = null; try { //try to look the user up User user = userManager.findUser(username); if (user instanceof LdapUser) { LdapUser ldapUser = LdapUser.class.cast(user); Attribute dnAttribute = ldapUser.getOriginalAttributes().get(getLdapDnAttribute()); if (dnAttribute != null) { groupEntry = String.class.cast(dnAttribute.get()); } } } catch (UserNotFoundException e) { log.warn("Failed to look up user {}. Computing distinguished name manually", username, e); } catch (UserManagerException e) { log.warn("Failed to look up user {}. Computing distinguished name manually", username, e); } if (groupEntry == null) { //failed to look up the user's groupEntry directly StringBuilder builder = new StringBuilder(); String posixGroup = "posixGroup"; if (posixGroup.equals(getLdapGroupClass())) { builder.append(username); } else { builder.append(this.userIdAttribute).append("=").append(username).append(",") .append(getBaseDn()); } groupEntry = builder.toString(); } String filter = new StringBuilder().append("(&").append("(objectClass=" + getLdapGroupClass() + ")") .append("(").append(getLdapGroupMember()).append("=").append(Rdn.escapeValue(groupEntry)) .append(")").append(")").toString(); log.debug("filter: {}", filter); namingEnumeration = context.search(getGroupsDn(), filter, searchControls); while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); List<String> allMembers = new ArrayList<String>(); Attribute uniqueMemberAttr = searchResult.getAttributes().get(getLdapGroupMember()); if (uniqueMemberAttr != null) { NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr .getAll(); while (allMembersEnum.hasMore()) { String userName = allMembersEnum.next(); //the original dn allMembers.add(userName); // uid=blabla we only want bla bla userName = StringUtils.substringAfter(userName, "="); userName = StringUtils.substringBefore(userName, ","); allMembers.add(userName); } close(allMembersEnum); } if (allMembers.contains(username)) { String groupName = searchResult.getName(); // cn=blabla we only want bla bla groupName = StringUtils.substringAfter(groupName, "="); userGroups.add(groupName); } else if (allMembers.contains(groupEntry)) { String groupName = searchResult.getName(); // cn=blabla we only want bla bla groupName = StringUtils.substringAfter(groupName, "="); userGroups.add(groupName); } } return userGroups; } catch (LdapException e) { throw new MappingException(e.getMessage(), e); } catch (NamingException e) { throw new MappingException(e.getMessage(), e); } finally { close(namingEnumeration); } }
From source file:nl.knaw.dans.common.ldap.repo.LdapMapper.java
private void setFields(T instance, Attributes attrs) throws LdapMappingException { for (Field field : getAnnotatedFields()) { String attrID = field.getAnnotation(LdapAttribute.class).id(); if (!field.getAnnotation(LdapAttribute.class).oneWayEncrypted() && !ENCRYPTION_ALGORITHM.equals(field.getAnnotation(LdapAttribute.class).encrypted())) { Attribute attr = attrs.get(attrID); Class<?> type = field.getType(); Object value = null;//from w w w. j a va 2 s . c o m Class valueTranslatorClass = field.getAnnotation(LdapAttribute.class).valueTranslator(); try { if (attr != null) { value = getSingleValue(type, attr.get()); if (value != null) { LdapAttributeValueTranslator valueTranslator = getValueTranslator(valueTranslatorClass); value = valueTranslator.fromLdap(value); field.setAccessible(true); field.set(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 (ClassCastException e) { final String msg = "Expected " + type + " but was " + value; logger.error(msg); 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:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java
@Override public void doUpdateCredentialByAdmin(String userName, Object newCredential) throws UserStoreException { if (!isSSLConnection) { logger.warn("Unsecured connection is being used. Password operations will fail"); }// w w w . j a v a 2s. c o m DirContext dirContext = this.connectionSource.getContext(); String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userListFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER); String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE); String searchFilter = "(&" + userListFilter + "(" + userNameAttribute + "=" + escapeSpecialCharactersForFilter(userName) + "))"; SearchControls searchControl = new SearchControls(); String[] returningAttributes = { "CN" }; searchControl.setReturningAttributes(returningAttributes); searchControl.setSearchScope(SearchControls.SUBTREE_SCOPE); DirContext subDirContext = null; NamingEnumeration<SearchResult> searchResults = null; try { // search the user with UserNameAttribute and obtain its CN attribute searchResults = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControl); SearchResult user = null; int count = 0; while (searchResults.hasMore()) { if (count > 0) { throw new UserStoreException( "There are more than one result in the user store " + "for user: " + userName); } user = searchResults.next(); count++; } String userCNValue = null; if (user.getAttributes() != null) { Attribute cnAttribute = user.getAttributes().get("CN"); if (cnAttribute != null) { userCNValue = (String) cnAttribute.get(); } else { throw new UserStoreException("Can not update credential: CN attribute is null"); } } ModificationItem[] mods = null; if (newCredential != null) { mods = new ModificationItem[1]; mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE, createUnicodePassword((String) newCredential))); subDirContext = (DirContext) dirContext.lookup(searchBase); subDirContext.modifyAttributes("CN" + "=" + escapeSpecialCharactersForDN(userCNValue), mods); } } catch (NamingException e) { String error = "Can not access the directory service for user : " + userName; if (logger.isDebugEnabled()) { logger.debug(error, e); } throw new UserStoreException(error, e); } finally { JNDIUtil.closeNamingEnumeration(searchResults); JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }
From source file:de.fiz.ddb.aas.utils.LDAPEngineUtility.java
/** * get attribute values of given resource and attributes. * //from ww w . j a va 2s. com * @param scope * scope * @param id * id of resource * @param attributeName * attribute-name to retrieve * * @return String attribute value * @throws NamingException * @throws IllegalAccessException */ public Map<String, String> getResourceAttributes(Scope scope, String id, String[] attributeNames) throws NamingException, IllegalAccessException { Map<String, String> returnMap = new HashMap<String, String>(); String baseDn = null; String filter = getIdFilter(scope, id); int levelScope = 0; InitialLdapContext ctx = null; NamingEnumeration<SearchResult> results = null; if (scope == Scope.ORGANIZATION) { baseDn = LDAPConnector.getSingletonInstance().getInstitutionBaseDN(); levelScope = SearchControls.SUBTREE_SCOPE; } else if (scope == Scope.PERSON) { baseDn = LDAPConnector.getSingletonInstance().getPersonBaseDN(); levelScope = SearchControls.ONELEVEL_SCOPE; } try { ctx = LDAPConnector.getSingletonInstance().takeCtx(); results = query(ctx, baseDn, filter, attributeNames, levelScope); if (results.hasMore()) { SearchResult searchResult = results.next(); if (results.hasMore()) { throw new IllegalAccessException("found more than one object with id=" + id); } Attributes attributes = searchResult.getAttributes(); for (int i = 0; i < attributeNames.length; i++) { Attribute attribute = attributes.get(attributeNames[i]); if (attribute == null) { returnMap.put(attributeNames[i], (String) null); } else { returnMap.put(attributeNames[i], (String) attribute.get()); } } return returnMap; } else { throw new NameNotFoundException("id not found"); } } finally { if (ctx != null) { try { LDAPConnector.getSingletonInstance().putCtx(ctx); } catch (IllegalAccessException ex) { LOG.log(Level.SEVERE, null, ex); } } if (results != null) { try { results.close(); } catch (NamingException e) { LOG.log(Level.WARNING, null, e); } } } }
From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java
private void parseMembers(String userDN, Set<GrantedAuthority> groups, NamingEnumeration<SearchResult> renum) throws NamingException { try {/*from ww w. j a v a2s. c o m*/ while (renum.hasMore()) { Attributes a = renum.next().getAttributes(); Attribute cn = a.get("cn"); if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine(userDN + " is a member of " + cn); groups.add(new GrantedAuthorityImpl(cn.get().toString())); } } catch (PartialResultException e) { // See JENKINS-42687. Just log the exception. Sometimes all the groups are correctly // retrieved but this Exception is launched as a last element of the NamingEnumeration // Even if it is really a PartialResultException, I don't see why this should be a blocker // I think a better approach is to log the Exception and continue LOGGER.log(Level.WARNING, String.format("JENKINS-42687 Might be more members for user %s", userDN), e); } }
From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java
/** * */// w w w. jav a 2 s . co m public void doUpdateCredential(String userName, Object newCredential, Object oldCredential) throws UserStoreException { if (!isSSLConnection) { logger.warn("Unsecured connection is being used. Password operations will fail"); } DirContext dirContext = this.connectionSource.getContext(); String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userListFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER); String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE); // String searchFilter = // realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); String searchFilter = "(&" + userListFilter + "(" + userNameAttribute + "=" + escapeSpecialCharactersForFilter(userName) + "))"; SearchControls searchControl = new SearchControls(); String[] returningAttributes = { "CN" }; searchControl.setReturningAttributes(returningAttributes); searchControl.setSearchScope(SearchControls.SUBTREE_SCOPE); DirContext subDirContext = null; NamingEnumeration<SearchResult> searchResults = null; try { // search the user with UserNameAttribute and obtain its CN attribute searchResults = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControl); SearchResult user = null; int count = 0; while (searchResults.hasMore()) { if (count > 0) { throw new UserStoreException( "There are more than one result in the user store " + "for user: " + userName); } user = searchResults.next(); count++; } String userCNValue = null; if (user.getAttributes() != null) { Attribute cnAttribute = user.getAttributes().get("CN"); if (cnAttribute != null) { userCNValue = (String) cnAttribute.get(); } else { throw new UserStoreException("Can not update credential: CN attribute is null"); } } ModificationItem[] mods = null; // The user tries to change his own password if (oldCredential != null && newCredential != null) { mods = new ModificationItem[1]; /* * byte[] oldUnicodePassword = createUnicodePassword((String) oldCredential); byte[] * newUnicodePassword = createUnicodePassword((String) newCredential); */ mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE, createUnicodePassword((String) newCredential))); /* * mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute( * LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE, newUnicodePassword)); */ } subDirContext = (DirContext) dirContext.lookup(searchBase); subDirContext.modifyAttributes("CN" + "=" + escapeSpecialCharactersForDN(userCNValue), mods); } catch (NamingException e) { String error = "Can not access the directory service for user : " + userName; if (logger.isDebugEnabled()) { logger.debug(error, e); } throw new UserStoreException(error, e); } finally { JNDIUtil.closeNamingEnumeration(searchResults); JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }
From source file:edu.internet2.middleware.subject.provider.LdapSourceAdapter.java
/** * Try to get more attributes for the argument subject. (from name) */// ww w.j a va2 s . c o m protected Map getAllAttributes(LdapSubject subject) { Map attributes = new HashMap(); log.debug("getAllAttributes for " + subject.getName()); Search search = getSearch("searchSubjectAttributes"); if (search == null) { log.error("searchType: \"searchSubjectAttributes\" not defined."); return attributes; } try { Attributes ldapAttributes = getLdapUnique(search, subject.getName(), allAttributeNames); for (NamingEnumeration e = ldapAttributes.getAll(); e.hasMore();) { Attribute attr = (Attribute) e.next(); String attrName = attr.getID(); // special case the basic ones if (attrName.equals(subjectIDAttributeName)) continue; // already have if (attrName.equals(nameAttributeName)) continue; // already have if (attrName.equals(descriptionAttributeName)) { subject.setDescription((String) attr.get()); continue; } Set values = new HashSet(); for (NamingEnumeration en = attr.getAll(); en.hasMore();) { Object value = en.next(); values.add(value.toString()); } attributes.put(attrName, values); } subject.setAttributes(attributes); } catch (SubjectNotFoundException ex) { log.error("SubjectNotFound: " + subject.getId() + " " + ex.getMessage(), ex); } catch (SubjectNotUniqueException ex) { log.error("SubjectNotUnique: " + subject.getId() + " " + ex.getMessage(), ex); } catch (NamingException ex) { log.error("LDAP Naming Except: " + ex.getMessage(), ex); } return attributes; }
From source file:org.apache.james.user.ldap.ReadOnlyUsersLDAPRepository.java
/** * For a given name, this method makes ldap search in userBase with filter {@link #userIdAttribute}=name and objectClass={@link #userObjectClass} * and builds {@link User} based on search result. * * @param name//from w ww.j a v a2s. com * The userId which should be value of the field {@link #userIdAttribute} * @return A {@link ReadOnlyLDAPUser} instance which is initialized with the * userId of this user and ldap connection information with which * the user was searched. Return null if such a user was not found. * @throws NamingException * Propagated by the underlying LDAP communication layer. */ private ReadOnlyLDAPUser searchAndBuildUser(String name) throws NamingException { SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(new String[] { userIdAttribute }); sc.setCountLimit(1); StringBuilder builderFilter = new StringBuilder("(&("); builderFilter.append(userIdAttribute).append("=").append(name).append(")").append("(objectClass=") .append(userObjectClass).append(")"); if (StringUtils.isNotEmpty(filter)) { builderFilter.append(filter).append(")"); } else { builderFilter.append(")"); } NamingEnumeration<SearchResult> sr = ldapContext.search(userBase, builderFilter.toString(), sc); if (!sr.hasMore()) return null; SearchResult r = sr.next(); Attribute userName = r.getAttributes().get(userIdAttribute); if (!restriction.isActivated() || userInGroupsMembershipList(r.getNameInNamespace(), restriction.getGroupMembershipLists(ldapContext))) return new ReadOnlyLDAPUser(userName.get().toString(), r.getNameInNamespace(), ldapContext); return null; }