List of usage examples for javax.naming.directory Attribute getAll
NamingEnumeration<?> getAll() throws NamingException;
From source file:nl.nn.adapterframework.ldap.LdapSender.java
private String performOperationUpdate(String entryName, ParameterResolutionContext prc, Map paramValueMap, Attributes attrs) throws SenderException, ParameterException { String entryNameAfter = entryName; if (paramValueMap != null) { String newEntryName = (String) paramValueMap.get("newEntryName"); if (newEntryName != null && StringUtils.isNotEmpty(newEntryName)) { if (log.isDebugEnabled()) log.debug("newEntryName=[" + newEntryName + "]"); DirContext dirContext = null; try { dirContext = getDirContext(paramValueMap); dirContext.rename(entryName, newEntryName); entryNameAfter = newEntryName; } catch (NamingException e) { String msg;/* w w w . j av a2 s .c o m*/ // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes: // 32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. // Sun: // [LDAP: error code 32 - No Such Object... if (e.getMessage().startsWith("[LDAP: error code 32 - ")) { msg = "Operation [" + getOperation() + "] failed - wrong entryName [" + entryName + "]"; } else { msg = "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]"; } storeLdapException(e, prc); throw new SenderException(msg, e); } finally { closeDirContext(dirContext); } } } if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) { NamingEnumeration na = attrs.getAll(); while (na.hasMoreElements()) { Attribute a = (Attribute) na.nextElement(); log.debug("Update attribute: " + a.getID()); NamingEnumeration values; try { values = a.getAll(); } catch (NamingException e1) { storeLdapException(e1, prc); throw new SenderException("cannot obtain values of Attribute [" + a.getID() + "]", e1); } while (values.hasMoreElements()) { Attributes partialAttrs = new BasicAttributes(); Attribute singleValuedAttribute; String id = a.getID(); Object value = values.nextElement(); if (log.isDebugEnabled()) { if (id.toLowerCase().contains("password") || id.toLowerCase().contains("pwd")) { log.debug("Update value: ***"); } else { log.debug("Update value: " + value); } } if (unicodePwd && "unicodePwd".equalsIgnoreCase(id)) { singleValuedAttribute = new BasicAttribute(id, encodeUnicodePwd(value)); } else { singleValuedAttribute = new BasicAttribute(id, value); } partialAttrs.put(singleValuedAttribute); DirContext dirContext = null; try { dirContext = getDirContext(paramValueMap); dirContext.modifyAttributes(entryNameAfter, DirContext.REPLACE_ATTRIBUTE, partialAttrs); } catch (NamingException e) { String msg; // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes: // 32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. // Sun: // [LDAP: error code 32 - No Such Object... if (e.getMessage().startsWith("[LDAP: error code 32 - ")) { msg = "Operation [" + getOperation() + "] failed - wrong entryName [" + entryNameAfter + "]"; } else { msg = "Exception in operation [" + getOperation() + "] entryName [" + entryNameAfter + "]"; } //result = DEFAULT_RESULT_UPDATE_NOK; storeLdapException(e, prc); throw new SenderException(msg, e); } finally { closeDirContext(dirContext); } } } return DEFAULT_RESULT; } else { DirContext dirContext = null; try { dirContext = getDirContext(paramValueMap); //dirContext.rename(newEntryName, oldEntryName); //result = DEFAULT_RESULT; dirContext.rename(entryName, entryName); return "<LdapResult>Deze functionaliteit is nog niet beschikbaar - naam niet veranderd.</LdapResult>"; } catch (NamingException e) { // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes: // 68 LDAP_ALREADY_EXISTS Indicates that the add operation attempted to add an entry that already exists, or that the modify operation attempted to rename an entry to the name of an entry that already exists. // Sun: // [LDAP: error code 68 - Entry Already Exists] if (!e.getMessage().startsWith("[LDAP: error code 68 - ")) { storeLdapException(e, prc); throw new SenderException(e); } return DEFAULT_RESULT_CREATE_NOK; } finally { closeDirContext(dirContext); } } }
From source file:org.apache.nifi.ldap.tenants.LdapUserGroupProvider.java
/** * Reloads the tenants./* w ww.ja va 2s . co m*/ */ private void load(final ContextSource contextSource) { // create the ldapTemplate based on the context source. use a single source context to use the same connection // to support paging when configured final SingleContextSource singleContextSource = new SingleContextSource(contextSource.getReadOnlyContext()); final LdapTemplate ldapTemplate = new LdapTemplate(singleContextSource); try { final List<User> userList = new ArrayList<>(); final List<Group> groupList = new ArrayList<>(); // group dn -> user identifiers lookup final Map<String, Set<String>> groupToUserIdentifierMappings = new HashMap<>(); // user dn -> user lookup final Map<String, User> userLookup = new HashMap<>(); if (performUserSearch) { // search controls final SearchControls userControls = new SearchControls(); userControls.setSearchScope(userSearchScope.ordinal()); // consider paging support for users final DirContextProcessor userProcessor; if (pageSize == null) { userProcessor = new NullDirContextProcessor(); } else { userProcessor = new PagedResultsDirContextProcessor(pageSize); } // looking for objects matching the user object class final AndFilter userFilter = new AndFilter(); userFilter.and(new EqualsFilter("objectClass", userObjectClass)); // if a filter has been provided by the user, we add it to the filter if (StringUtils.isNotBlank(userSearchFilter)) { userFilter.and(new HardcodedFilter(userSearchFilter)); } do { userList.addAll(ldapTemplate.search(userSearchBase, userFilter.encode(), userControls, new AbstractContextMapper<User>() { @Override protected User doMapFromContext(DirContextOperations ctx) { // get the user identity final String identity = getUserIdentity(ctx); // build the user final User user = new User.Builder().identifierGenerateFromSeed(identity) .identity(identity).build(); // store the user for group member later userLookup.put(getReferencedUserValue(ctx), user); if (StringUtils.isNotBlank(userGroupNameAttribute)) { final Attribute attributeGroups = ctx.getAttributes() .get(userGroupNameAttribute); if (attributeGroups == null) { logger.warn("User group name attribute [" + userGroupNameAttribute + "] does not exist. Ignoring group membership."); } else { try { final NamingEnumeration<String> groupValues = (NamingEnumeration<String>) attributeGroups .getAll(); while (groupValues.hasMoreElements()) { // store the group -> user identifier mapping groupToUserIdentifierMappings .computeIfAbsent(groupValues.next(), g -> new HashSet<>()) .add(user.getIdentifier()); } } catch (NamingException e) { throw new AuthorizationAccessException( "Error while retrieving user group name attribute [" + userIdentityAttribute + "]."); } } } return user; } }, userProcessor)); } while (hasMorePages(userProcessor)); } if (performGroupSearch) { final SearchControls groupControls = new SearchControls(); groupControls.setSearchScope(groupSearchScope.ordinal()); // consider paging support for groups final DirContextProcessor groupProcessor; if (pageSize == null) { groupProcessor = new NullDirContextProcessor(); } else { groupProcessor = new PagedResultsDirContextProcessor(pageSize); } // looking for objects matching the group object class AndFilter groupFilter = new AndFilter(); groupFilter.and(new EqualsFilter("objectClass", groupObjectClass)); // if a filter has been provided by the user, we add it to the filter if (StringUtils.isNotBlank(groupSearchFilter)) { groupFilter.and(new HardcodedFilter(groupSearchFilter)); } do { groupList.addAll(ldapTemplate.search(groupSearchBase, groupFilter.encode(), groupControls, new AbstractContextMapper<Group>() { @Override protected Group doMapFromContext(DirContextOperations ctx) { final String dn = ctx.getDn().toString(); // get the group identity final String name = getGroupName(ctx); // get the value of this group that may associate it to users final String referencedGroupValue = getReferencedGroupValue(ctx); if (!StringUtils.isBlank(groupMemberAttribute)) { Attribute attributeUsers = ctx.getAttributes().get(groupMemberAttribute); if (attributeUsers == null) { logger.warn("Group member attribute [" + groupMemberAttribute + "] does not exist. Ignoring group membership."); } else { try { final NamingEnumeration<String> userValues = (NamingEnumeration<String>) attributeUsers .getAll(); while (userValues.hasMoreElements()) { final String userValue = userValues.next(); if (performUserSearch) { // find the user by it's referenced attribute and add the identifier to this group final User user = userLookup.get(userValue); // ensure the user is known if (user != null) { groupToUserIdentifierMappings .computeIfAbsent(referencedGroupValue, g -> new HashSet<>()) .add(user.getIdentifier()); } else { logger.warn(String.format( "%s contains member %s but that user was not found while searching users. Ignoring group membership.", name, userValue)); } } else { // since performUserSearch is false, then the referenced group attribute must be blank... the user value must be the dn final String userDn = userValue; final String userIdentity; if (useDnForUserIdentity) { // use the user value to avoid the unnecessary look up userIdentity = userDn; } else { // lookup the user to extract the user identity userIdentity = getUserIdentity( (DirContextAdapter) ldapTemplate .lookup(userDn)); } // build the user final User user = new User.Builder() .identifierGenerateFromSeed(userIdentity) .identity(userIdentity).build(); // add this user userList.add(user); groupToUserIdentifierMappings .computeIfAbsent(referencedGroupValue, g -> new HashSet<>()) .add(user.getIdentifier()); } } } catch (NamingException e) { throw new AuthorizationAccessException( "Error while retrieving group name attribute [" + groupNameAttribute + "]."); } } } // build this group final Group.Builder groupBuilder = new Group.Builder() .identifierGenerateFromSeed(name).name(name); // add all users that were associated with this referenced group attribute if (groupToUserIdentifierMappings.containsKey(referencedGroupValue)) { groupToUserIdentifierMappings.remove(referencedGroupValue) .forEach(userIdentifier -> groupBuilder.addUser(userIdentifier)); } return groupBuilder.build(); } }, groupProcessor)); } while (hasMorePages(groupProcessor)); // any remaining groupDn's were referenced by a user but not found while searching groups groupToUserIdentifierMappings.forEach((referencedGroupValue, userIdentifiers) -> { logger.warn(String.format( "[%s] are members of %s but that group was not found while searching users. Ignoring group membership.", StringUtils.join(userIdentifiers, ", "), referencedGroupValue)); }); } else { // since performGroupSearch is false, then the referenced user attribute must be blank... the group value must be the dn // groups are not being searched so lookup any groups identified while searching users groupToUserIdentifierMappings.forEach((groupDn, userIdentifiers) -> { final String groupName; if (useDnForGroupName) { // use the dn to avoid the unnecessary look up groupName = groupDn; } else { groupName = getGroupName((DirContextAdapter) ldapTemplate.lookup(groupDn)); } // define the group final Group.Builder groupBuilder = new Group.Builder().identifierGenerateFromSeed(groupName) .name(groupName); // add each user userIdentifiers.forEach(userIdentifier -> groupBuilder.addUser(userIdentifier)); // build the group groupList.add(groupBuilder.build()); }); } // record the updated tenants tenants.set(new TenantHolder(new HashSet<>(userList), new HashSet<>(groupList))); } finally { singleContextSource.destroy(); } }
From source file:nl.nn.adapterframework.ldap.LdapSender.java
protected XmlBuilder attributesToXml(Attributes atts) throws NamingException { XmlBuilder attributesElem = new XmlBuilder("attributes"); NamingEnumeration all = atts.getAll(); while (all.hasMore()) { Attribute attribute = (Attribute) all.next(); XmlBuilder attributeElem = new XmlBuilder("attribute"); attributeElem.addAttribute("name", attribute.getID()); if (attribute.size() == 1 && attribute.get() != null) { attributeElem.addAttribute("value", attribute.get().toString()); } else {//from w ww .j a v a 2 s . c om NamingEnumeration values = attribute.getAll(); while (values.hasMore()) { Object value = values.next(); XmlBuilder itemElem = new XmlBuilder("item"); itemElem.addAttribute("value", value.toString()); attributeElem.addSubElement(itemElem); } } attributesElem.addSubElement(attributeElem); } return attributesElem; }
From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java
@SuppressWarnings("unchecked") protected List<String> getMandatoryAttributes(Attribute objectClassesAttribute) throws DirectoryException { try {//from w w w . j a va2 s . com List<String> mandatoryAttributes = new ArrayList<String>(); DirContext schema = dirContext.getSchema(""); List<String> objectClasses = new ArrayList<String>(); if (objectClassesAttribute == null) { // use the creation classes as reference schema for this entry objectClasses.addAll(Arrays.asList(getDirectory().getDescriptor().getCreationClasses())); } else { // introspec the objectClass definitions to find the mandatory // attributes for this entry NamingEnumeration<Object> values = null; try { values = (NamingEnumeration<Object>) objectClassesAttribute.getAll(); while (values.hasMore()) { objectClasses.add(values.next().toString().trim()); } } catch (NamingException e) { throw new DirectoryException(e); } finally { if (values != null) { values.close(); } } } objectClasses.remove("top"); for (String creationClass : objectClasses) { Attributes attributes = schema.getAttributes("ClassDefinition/" + creationClass); Attribute attribute = attributes.get("MUST"); if (attribute != null) { NamingEnumeration<String> values = (NamingEnumeration<String>) attribute.getAll(); try { while (values.hasMore()) { String value = values.next(); mandatoryAttributes.add(value); } } finally { values.close(); } } } return mandatoryAttributes; } catch (NamingException e) { throw new DirectoryException("getMandatoryAttributes failed", e); } }
From source file:org.swordess.ldap.odm.core.SessionImpl.java
private <T> T fromAttributesToEntity(Class<T> clazz, Attributes attributes) throws NamingException { try {/* w w w . j a va2 s .c om*/ Map.Entry<Object, SetterInterceptor> pair = EntityProxyFactory.getProxiedEntity(clazz); T entity = (T) pair.getKey(); EntityMetaData metaData = EntityMetaData.get(clazz); Set<String> multipleLdapAttrNames = new HashSet<String>(); for (EntityPropertyMetaData propMetaData : metaData) { if (propMetaData.isMultiple()) { multipleLdapAttrNames.add(propMetaData.getLdapPropName()); } } for (NamingEnumeration<? extends Attribute> attrs = attributes.getAll(); attrs.hasMore();) { Attribute attr = attrs.next(); EntityPropertyMetaData propMetaData = metaData.getProperty(attr.getID()); if (null == propMetaData) { // current attribute exist in LDAP but not defined in our // POJO. continue; } if (propMetaData.isId()) { propMetaData.setter().set(entity, attr.get()); if (entity instanceof Distinguishable) { ((Distinguishable) entity) .setDN(attr.getID() + "=" + attr.get().toString() + "," + metaData.context()); } } else { List<String> attrValues = new ArrayList<String>(); for (NamingEnumeration<?> all = attr.getAll(); all.hasMore();) { attrValues.add(propMetaData.getSyntaxer().ldapStringToJavaString(all.next().toString())); } if (!propMetaData.isReference()) { if (!propMetaData.isMultiple()) { propMetaData.setter().set(entity, attrValues.get(0)); } else { propMetaData.setter().set(entity, new MoniteredList<String>(attrValues)); multipleLdapAttrNames.remove(propMetaData.getLdapPropName()); } } else { final Class<?> referenceType = propMetaData.getValueClass(); if (!propMetaData.isMultiple()) { propMetaData.setter().set(entity, EntityProxyFactory.getLazyLoadingProxiedEntity(this, referenceType, attrValues.get(0))); } else { List references = new ArrayList(); for (String dn : attrValues) { references.add( EntityProxyFactory.getLazyLoadingProxiedEntity(this, referenceType, dn)); } propMetaData.setter().set(entity, new MoniteredList(references)); multipleLdapAttrNames.remove(propMetaData.getLdapPropName()); } } } /* * The rest attribute names in multipleLdapAttrNames are those * not presented in LDAP side. In order to track what changes * occurred to these attributes, we need to use MoniteredList. */ for (String notPresentedMultipleLdapAttrName : multipleLdapAttrNames) { metaData.getProperty(notPresentedMultipleLdapAttrName).setter().set(entity, new MoniteredList()); } } /* * Once all the properties have been initialized, we should turn on * the switch of SetterInterceptor to monitor changes. */ pair.getValue().turnOn(); return entity; } catch (NamingException e) { LogUtils.debug(LOG, "failed to go through attributes when fromAttributesToEntity"); throw e; } }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * @param searchBases Group search bases. * @param searchFilter Search filter for role search with membership value included. * @param searchCtls Search controls with returning attributes set. * @param property Role name attribute name in LDAP userstore. * @return List of roles according to the given filter. * @throws UserStoreException If an error occurs while retrieving data from LDAP context. *//*from w w w. j ava2 s.c o m*/ private List<String> getListOfNames(String searchBases, String searchFilter, SearchControls searchCtls, String property) throws UserStoreException { boolean debug = log.isDebugEnabled(); List<String> names = new ArrayList<>(); DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; if (debug) { log.debug("Result for searchBase: " + searchBases + " searchFilter: " + searchFilter + " property:" + property); } try { dirContext = connectionSource.getContext(); // handle multiple search bases String[] searchBaseArray = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR); for (String searchBase : searchBaseArray) { try { answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls); while (answer.hasMoreElements()) { SearchResult sr = answer.next(); if (sr.getAttributes() != null) { Attribute attr = sr.getAttributes().get(property); if (attr != null) { for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) { String name = (String) vals.nextElement(); if (debug) { log.debug("Found user: " + name); } names.add(name); } } } } } catch (NamingException e) { // ignore if (log.isDebugEnabled()) { log.debug(e); } } if (debug) { for (String name : names) { log.debug("Result : " + name); } } } return names; } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } }
From source file:org.craftercms.studio.impl.v1.service.security.DbWithLdapExtensionSecurityProvider.java
@Override public String authenticate(String username, String password) throws BadCredentialsException, AuthenticationSystemException { // Mapper for user data if user is successfully authenticated AuthenticatedLdapEntryContextMapper<User> mapper = new AuthenticatedLdapEntryContextMapper<User>() { @Override/*from ww w. j a v a2 s. c o m*/ public User mapWithContext(DirContext dirContext, LdapEntryIdentification ldapEntryIdentification) { try { // User entry - extract attributes DirContextOperations dirContextOperations = (DirContextOperations) dirContext .lookup(ldapEntryIdentification.getRelativeName()); Attributes attributes = dirContextOperations.getAttributes(); String emailAttribName = studioConfiguration.getProperty(SECURITY_LDAP_USER_ATTRIBUTE_EMAIL); String firstNameAttribName = studioConfiguration .getProperty(SECURITY_LDAP_USER_ATTRIBUTE_FIRST_NAME); String lastNameAttribName = studioConfiguration .getProperty(SECURITY_LDAP_USER_ATTRIBUTE_LAST_NAME); String siteIdAttribName = studioConfiguration.getProperty(SECURITY_LDAP_USER_ATTRIBUTE_SITE_ID); String groupNameAttribName = studioConfiguration .getProperty(SECURITY_LDAP_USER_ATTRIBUTE_GROUP_NAME); Attribute emailAttrib = attributes.get(emailAttribName); Attribute firstNameAttrib = attributes.get(firstNameAttribName); Attribute lastNameAttrib = attributes.get(lastNameAttribName); Attribute siteIdAttrib = attributes.get(siteIdAttribName); Attribute groupNameAttrib = attributes.get(groupNameAttribName); User user = new User(); user.setGroups(new ArrayList<>()); user.setActive(1); user.setUsername(username); if (emailAttrib != null && emailAttrib.get() != null) { user.setEmail(emailAttrib.get().toString()); } else { logger.error("No LDAP attribute " + emailAttribName + " found for username " + username + ". User will not be imported into DB."); return null; } if (firstNameAttrib != null && firstNameAttrib.get() != null) { user.setFirstname(firstNameAttrib.get().toString()); } else { logger.warn("No LDAP attribute " + firstNameAttribName + " found for username " + username); } if (lastNameAttrib != null && lastNameAttrib.get() != null) { user.setLastname(lastNameAttrib.get().toString()); } else { logger.warn("No LDAP attribute " + lastNameAttribName + " found for username " + username); } if (siteIdAttrib != null && siteIdAttrib.get() != null) { Map<String, Object> params = new HashMap<>(); NamingEnumeration siteIdValues = siteIdAttrib.getAll(); while (siteIdValues.hasMore()) { Object siteIdObj = siteIdValues.next(); if (siteIdObj != null) { String[] siteIdAndGroupName = extractSiteIdAndGroupNameFromAttributeValue( siteIdObj.toString()); if (siteIdAndGroupName.length > 0) { params.put("siteId", siteIdAndGroupName[0]); SiteFeed siteFeed = siteFeedMapper.getSite(params); if (siteFeed != null) { // Add groups, first the one that's specific to the site if (siteIdAndGroupName.length > 1) { addGroupToUser(user, siteIdAndGroupName[1], siteFeed); } extractGroupsFromAttribute(user, groupNameAttribName, groupNameAttrib, siteFeed); } else { logger.warn("Not site found for ID " + siteIdAndGroupName[0]); } } } } } else { String defaultSiteId = studioConfiguration.getProperty(SECURITY_LDAP_DEFAULT_SITE_ID); logger.debug("Assigning user " + username + " to default site " + defaultSiteId); Map<String, Object> params = new HashMap<>(); params.put("siteId", defaultSiteId); SiteFeed siteFeed = siteFeedMapper.getSite(params); if (siteFeed != null) { extractGroupsFromAttribute(user, groupNameAttribName, groupNameAttrib, siteFeed); } else { logger.warn("No site found for default site ID " + defaultSiteId); } } return user; } catch (NamingException e) { logger.error("Error getting details from LDAP for username " + username, e); return null; } } }; // Create ldap query to authenticate user LdapQuery ldapQuery = query().where(studioConfiguration.getProperty(SECURITY_LDAP_USER_ATTRIBUTE_USERNAME)) .is(username); User user; try { user = ldapTemplate.authenticate(ldapQuery, password, mapper); } catch (EmptyResultDataAccessException e) { logger.info("User " + username + " not found with external security provider. Trying to authenticate against studio database"); // When user not found try to authenticate against studio database return super.authenticate(username, password); } catch (CommunicationException e) { logger.info("Failed to connect with external security provider. " + "Trying to authenticate against studio database"); // When user not found try to authenticate against studio database return super.authenticate(username, password); } catch (AuthenticationException e) { logger.error("Authentication failed with the LDAP system", e); throw new BadCredentialsException(); } catch (Exception e) { logger.error("Authentication failed with the LDAP system", e); throw new AuthenticationSystemException("Authentication failed with the LDAP system", e); } if (user != null) { // When user authenticated against LDAP, upsert user data into studio database if (super.userExists(username)) { try { boolean success = updateUserInternal(user.getUsername(), user.getFirstname(), user.getLastname(), user.getEmail()); if (success) { ActivityService.ActivityType activityType = ActivityService.ActivityType.UPDATED; Map<String, String> extraInfo = new HashMap<>(); extraInfo.put(DmConstants.KEY_CONTENT_TYPE, StudioConstants.CONTENT_TYPE_USER); activityService.postActivity(getSystemSite(), user.getUsername(), user.getUsername(), activityType, ActivityService.ActivitySource.API, extraInfo); } } catch (UserNotFoundException e) { logger.error( "Error updating user " + username + " with data from external authentication provider", e); throw new AuthenticationSystemException( "Error updating user " + username + " with data from external authentication provider", e); } } else { try { boolean success = createUser(user.getUsername(), password, user.getFirstname(), user.getLastname(), user.getEmail(), true); if (success) { ActivityService.ActivityType activityType = ActivityService.ActivityType.CREATED; Map<String, String> extraInfo = new HashMap<>(); extraInfo.put(DmConstants.KEY_CONTENT_TYPE, StudioConstants.CONTENT_TYPE_USER); activityService.postActivity(getSystemSite(), user.getUsername(), user.getUsername(), activityType, ActivityService.ActivitySource.API, extraInfo); } } catch (UserAlreadyExistsException e) { logger.error("Error adding user " + username + " from external authentication provider", e); throw new AuthenticationSystemException( "Error adding user " + username + " from external authentication provider", e); } } for (Group group : user.getGroups()) { try { upsertUserGroup(group.getSite(), group.getName(), user.getUsername()); } catch (GroupAlreadyExistsException | SiteNotFoundException | UserNotFoundException | UserAlreadyExistsException | GroupNotFoundException e) { logger.error("Failed to upsert user groups data from LDAP", e); } } String token = createToken(user); storeSessionTicket(token); storeSessionUsername(username); return token; } else { logger.error("Failed to retrieve LDAP user details"); throw new AuthenticationSystemException("Failed to retrieve LDAP user details"); } }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * {@inheritDoc}// w w w . j a va 2s .c om */ public Map<String, String> getUserPropertyValues(String userName, String[] propertyNames) throws UserStoreException { String userAttributeSeparator = ","; String userDN = null; // read list of patterns from user-mgt.xml String patterns = userStoreProperties.get(LDAPConstants.USER_DN_PATTERN); if (patterns != null && !patterns.isEmpty()) { if (log.isDebugEnabled()) { log.debug("Using User DN Patterns " + patterns); } if (patterns.contains(CommonConstants.XML_PATTERN_SEPERATOR)) { userDN = getNameInSpaceForUserName(userName); } else { userDN = MessageFormat.format(patterns, escapeSpecialCharactersForDN(userName)); } } Map<String, String> values = new HashMap<>(); DirContext dirContext = this.connectionSource.getContext(); String userSearchFilter = userStoreProperties.get(LDAPConstants.USER_NAME_SEARCH_FILTER); String searchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); NamingEnumeration<?> answer = null; NamingEnumeration<?> attrs = null; NamingEnumeration<?> allAttrs = null; try { if (userDN != null) { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); if (propertyNames[0].equals(CommonConstants.WILD_CARD_FILTER)) { propertyNames = null; } searchCtls.setReturningAttributes(propertyNames); try { answer = dirContext.search(escapeDNForSearch(userDN), searchFilter, searchCtls); } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error occurred while searching directory context for user : " + userDN + " searchFilter : " + searchFilter; if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error occurred while searching directory context for user : " + userDN + " searchFilter : " + searchFilter; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } } else { answer = this.searchForUser(searchFilter, propertyNames, dirContext); } assert answer != null; while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); Attributes attributes = sr.getAttributes(); if (attributes != null) { for (allAttrs = attributes.getAll(); allAttrs.hasMore();) { Attribute attribute = (Attribute) allAttrs.next(); if (attribute != null) { StringBuilder attrBuffer = new StringBuilder(); for (attrs = attribute.getAll(); attrs.hasMore();) { Object attObject = attrs.next(); String attr = null; if (attObject instanceof String) { attr = (String) attObject; } else if (attObject instanceof byte[]) { //if the attribute type is binary base64 encoded string will be returned attr = new String(Base64.encodeBase64((byte[]) attObject), "UTF-8"); } if (attr != null && attr.trim().length() > 0) { String attrSeparator = userStoreProperties.get(MULTI_ATTRIBUTE_SEPARATOR); if (attrSeparator != null && !attrSeparator.trim().isEmpty()) { userAttributeSeparator = attrSeparator; } attrBuffer.append(attr).append(userAttributeSeparator); } String value = attrBuffer.toString(); /* * Length needs to be more than userAttributeSeparator.length() for a valid * attribute, since we * attach userAttributeSeparator */ if (value.trim().length() > userAttributeSeparator.length()) { value = value.substring(0, value.length() - userAttributeSeparator.length()); values.put(attribute.getID(), value); } } } } } } } catch (NamingException e) { String errorMessage = "Error occurred while getting user property values for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } catch (UnsupportedEncodingException e) { String errorMessage = "Error occurred while Base64 encoding property values for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { // close the naming enumeration and free up resource JNDIUtil.closeNamingEnumeration(attrs); JNDIUtil.closeNamingEnumeration(answer); // close directory context JNDIUtil.closeContext(dirContext); } return values; }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * {@inheritDoc}// w ww . j av a2 s. c o m */ @Override public String[] doGetUserListOfRole(String roleName, int maxItemLimit) throws UserStoreException { boolean debug = log.isDebugEnabled(); List<String> userList = new ArrayList<String>(); String[] names = new String[0]; int givenMax = CommonConstants.MAX_USER_ROLE_LIST; int searchTime = CommonConstants.MAX_SEARCH_TIME; try { givenMax = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_USER_LIST)); } catch (Exception e) { givenMax = CommonConstants.MAX_USER_ROLE_LIST; } try { searchTime = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_SEARCH_TIME)); } catch (Exception e) { searchTime = CommonConstants.MAX_SEARCH_TIME; } if (maxItemLimit <= 0 || maxItemLimit > givenMax) { maxItemLimit = givenMax; } DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; try { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setTimeLimit(searchTime); searchCtls.setCountLimit(maxItemLimit); String searchFilter = userStoreProperties.get(LDAPConstants.GROUP_NAME_LIST_FILTER); String roleNameProperty = userStoreProperties.get(LDAPConstants.GROUP_NAME_ATTRIBUTE); searchFilter = "(&" + searchFilter + "(" + roleNameProperty + "=" + escapeSpecialCharactersForFilter(roleName) + "))"; String membershipProperty = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE); String returnedAtts[] = { membershipProperty }; searchCtls.setReturningAttributes(returnedAtts); List<String> userDNList = new ArrayList<String>(); SearchResult sr = null; dirContext = connectionSource.getContext(); // handling multiple search bases String searchBases = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE); String[] roleSearchBaseArray = searchBases.split("#"); for (String searchBase : roleSearchBaseArray) { if (debug) { log.debug("Searching role: " + roleName + " SearchBase: " + searchBase + " SearchFilter: " + searchFilter); } try { // read the DN of users who are members of the group answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls); int count = 0; if (answer.hasMore()) { // to check if there is a result while (answer.hasMore()) { // to check if there are more than one group if (count > 0) { throw new UserStoreException("More than one group exist with name"); } sr = answer.next(); count++; } break; } } catch (NamingException e) { // ignore if (log.isDebugEnabled()) { log.debug(e); } } } if (debug) { log.debug("Found role: " + sr.getNameInNamespace()); } // read the member attribute and get DNs of the users Attributes attributes = sr.getAttributes(); if (attributes != null) { NamingEnumeration attributeEntry = null; for (attributeEntry = attributes.getAll(); attributeEntry.hasMore();) { Attribute valAttribute = (Attribute) attributeEntry.next(); if (membershipProperty.equals(valAttribute.getID())) { NamingEnumeration values = null; for (values = valAttribute.getAll(); values.hasMore();) { String value = values.next().toString(); if (userDNList.size() >= maxItemLimit) { break; } userDNList.add(value); if (debug) { log.debug("Found attribute: " + membershipProperty + " value: " + value); } } } } } if (MEMBER_UID.equals(userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE))) { /* when the GroupEntryObjectClass is posixGroup, membership attribute is memberUid. We have to retrieve the DN using the memberUid. This procedure has to make an extra call to ldap. alternatively this can be done with a single ldap search using the memberUid and retrieving the display name and username. */ List<String> userDNListNew = new ArrayList<>(); for (String user : userDNList) { String userDN = getNameInSpaceForUserName(user); userDNListNew.add(userDN); } userDNList = userDNListNew; } // iterate over users' DN list and get userName and display name // attribute values String userNameProperty = userStoreProperties.get(LDAPConstants.USER_NAME_ATTRIBUTE); String displayNameAttribute = userStoreProperties.get(LDAPConstants.DISPLAY_NAME_ATTRIBUTE); String[] returnedAttributes = { userNameProperty, displayNameAttribute }; for (String user : userDNList) { if (debug) { log.debug("Getting name attributes of: " + user); } Attributes userAttributes; try { // '\' and '"' characters need another level of escaping before searching userAttributes = dirContext.getAttributes(escapeDNForSearch(user), returnedAttributes); String displayName = null; String userName = null; if (userAttributes != null) { Attribute userNameAttribute = userAttributes.get(userNameProperty); if (userNameAttribute != null) { userName = (String) userNameAttribute.get(); if (debug) { log.debug("UserName: " + userName); } } if (org.apache.commons.lang.StringUtils.isNotEmpty(displayNameAttribute)) { Attribute displayAttribute = userAttributes.get(displayNameAttribute); if (displayAttribute != null) { displayName = (String) displayAttribute.get(); } if (debug) { log.debug("DisplayName: " + displayName); } } } // Username will be null in the special case where the // username attribute has changed to another // and having different userNameProperty than the current // user-mgt.xml if (userName != null) { user = UserStoreUtils.getCombinedName(userName, displayName); userList.add(user); if (debug) { log.debug(user + " is added to the result list"); } } else { if (log.isDebugEnabled()) { log.debug( "User " + user + " doesn't have the user name property : " + userNameProperty); } } } catch (NamingException e) { if (log.isDebugEnabled()) { log.debug("Error in reading user information in the user store for the user " + user + e.getMessage(), e); } } } names = userList.toArray(new String[userList.size()]); } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error in reading user information in the user store"; if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error in reading user information in the user store"; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return names; }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
@Override public void doUpdateCredentialByAdmin(String userName, Object newCredential) throws UserStoreException { DirContext dirContext = this.connectionSource.getContext(); DirContext subDirContext = null; // first search the existing user entry. String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(new String[] { "userPassword" }); NamingEnumeration<SearchResult> namingEnumeration = null; NamingEnumeration passwords = null; try {//from w ww . j ava2 s . c om namingEnumeration = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControls); // here we assume only one user // TODO: what to do if there are more than one user // there can be only only on user SearchResult searchResult = null; while (namingEnumeration.hasMore()) { searchResult = namingEnumeration.next(); String passwordHashMethod = realmConfig.getUserStoreProperty(PASSWORD_HASH_METHOD); if (!UserCoreConstants.RealmConfig.PASSWORD_HASH_METHOD_PLAIN_TEXT .equalsIgnoreCase(passwordHashMethod)) { Attributes attributes = searchResult.getAttributes(); Attribute userPassword = attributes.get("userPassword"); // When admin changes other user passwords he do not have to // provide the old password. Here it is only possible to have one password, if there // are more every one should match with the given old password passwords = userPassword.getAll(); if (passwords.hasMore()) { byte[] byteArray = (byte[]) passwords.next(); String password = new String(byteArray); if (password.startsWith("{")) { passwordHashMethod = password.substring(password.indexOf('{') + 1, password.indexOf('}')); } } } String dnName = searchResult.getName(); subDirContext = (DirContext) dirContext.lookup(searchBase); Attribute passwordAttribute = new BasicAttribute("userPassword"); passwordAttribute.add( UserCoreUtil.getPasswordToStore((String) newCredential, passwordHashMethod, kdcEnabled)); BasicAttributes basicAttributes = new BasicAttributes(true); basicAttributes.put(passwordAttribute); subDirContext.modifyAttributes(dnName, DirContext.REPLACE_ATTRIBUTE, basicAttributes); } // we check whether both carbon admin entry and ldap connection // entry are the same if (searchResult.getNameInNamespace() .equals(realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_NAME))) { this.connectionSource.updateCredential((String) newCredential); } } catch (NamingException e) { String errorMessage = "Can not access the directory service for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(passwords); JNDIUtil.closeNamingEnumeration(namingEnumeration); JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }