Java Code Examples for javax.naming.directory.SearchResult#getAttributes()

The following examples show how to use javax.naming.directory.SearchResult#getAttributes() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LdapAuthenticator.java    From dropwizard-auth-ldap with Apache License 2.0 6 votes vote down vote up
private Set<String> getGroupMembershipsIntersectingWithRestrictedGroups(AutoclosingLdapContext context, String userName) throws NamingException {

        userName = userNameBaseOnGroupClass(userName);

        final String filter = String.format("(&(%s=%s)(objectClass=%s))", configuration.getGroupMembershipAttribute(), userName, configuration.getGroupClassName());
        final NamingEnumeration<SearchResult> result = context.search(configuration.getGroupFilter(), filter, new SearchControls());

        ImmutableSet.Builder<String> overlappingGroups = ImmutableSet.builder();
        try {
            while (result.hasMore()) {
                SearchResult next = result.next();
                if (next.getAttributes() != null && next.getAttributes().get(configuration.getGroupNameAttribute()) != null) {
                    String group = (String) next.getAttributes().get(configuration.getGroupNameAttribute()).get(0);
                    if (configuration.getRestrictToGroups().isEmpty() ||
                            configuration.getRestrictToGroups().contains(group)) {
                        overlappingGroups.add(group);
                    }
                }
            }
            return overlappingGroups.build();
        } finally {
            result.close();
        }
    }
 
Example 2
Source File: LdapManager.java    From fess with Apache License 2.0 6 votes vote down vote up
protected List<Object> getAttributeValueList(final List<SearchResult> result, final String name) {
    try {
        for (final SearchResult srcrslt : result) {
            final Attributes attrs = srcrslt.getAttributes();

            final Attribute attr = attrs.get(name);
            if (attr == null) {
                continue;
            }

            final List<Object> attrList = new ArrayList<>();
            for (int i = 0; i < attr.size(); i++) {
                final Object attrValue = attr.get(i);
                if (attrValue != null) {
                    attrList.add(attrValue);
                }
            }
            return attrList;
        }
        return Collections.emptyList();
    } catch (final NamingException e) {
        throw new LdapOperationException("Failed to parse attribute values for " + name, e);
    }
}
 
Example 3
Source File: OpenLdapUserManagerImpl.java    From cosmic with Apache License 2.0 6 votes vote down vote up
protected LdapUser createUser(final SearchResult result) throws NamingException {
    final Attributes attributes = result.getAttributes();

    final String username = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getUsernameAttribute());
    final String email = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getEmailAttribute());
    final String firstname = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getFirstnameAttribute());
    final String lastname = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getLastnameAttribute());
    final String principal = result.getNameInNamespace();

    String domain = principal.replace("cn=" + LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getCommonNameAttribute()) + ",", "");
    domain = domain.replace("," + _ldapConfiguration.getBaseDn(), "");
    domain = domain.replace("ou=", "");

    final boolean disabled = isUserDisabled(result);

    return new LdapUser(username, email, firstname, lastname, principal, domain, disabled);
}
 
Example 4
Source File: LdapDao.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
public List<T> findAll(final DirContext ctx, final String organizationalUnit) throws NamingException
{
  final LinkedList<T> list = new LinkedList<T>();
  NamingEnumeration< ? > results = null;
  final SearchControls controls = new SearchControls();
  controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
  final String searchBase = getSearchBase(organizationalUnit);
  results = ctx.search(searchBase, "(objectclass=" + getObjectClass() + ")", controls);
  while (results.hasMore()) {
    final SearchResult searchResult = (SearchResult) results.next();
    final String dn = searchResult.getName();
    final Attributes attributes = searchResult.getAttributes();
    list.add(mapToObject(dn, searchBase, attributes));
  }
  return list;
}
 
Example 5
Source File: LdapManager.java    From fess with Apache License 2.0 6 votes vote down vote up
protected void processSearchRoles(final List<SearchResult> result, final Consumer<String> consumer) throws NamingException {
    for (final SearchResult srcrslt : result) {
        final Attributes attrs = srcrslt.getAttributes();

        //get group attr
        final Attribute attr = attrs.get(fessConfig.getLdapMemberofAttribute());
        if (attr == null) {
            continue;
        }

        for (int i = 0; i < attr.size(); i++) {
            final Object attrValue = attr.get(i);
            if (attrValue != null) {
                final String entryDn = attrValue.toString();

                if (logger.isDebugEnabled()) {
                    logger.debug("entryDn: {}", entryDn);
                }
                consumer.accept(entryDn);
            }
        }
    }
}
 
Example 6
Source File: LDAPManager.java    From Benchmark with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Search LDAPPerson by name
 * 
 * @param person
 *            to search
 * @return true if record found
 */
@SuppressWarnings("unused")
private boolean search(LDAPPerson person) {
	try {

		DirContext ctx = getDirContext();
		String base = "ou=users,ou=system";

		SearchControls sc = new SearchControls();
		sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

		String filter = "(&(objectclass=person)(uid=" + ESAPI_Encoder.encodeForLDAP(person.getName()) + "))";

		NamingEnumeration<SearchResult> results = ctx.search(base, filter, sc);

		while (results.hasMore()) {
			SearchResult sr = (SearchResult) results.next();
			Attributes attrs = sr.getAttributes();

			Attribute attr = attrs.get("uid");
			if (attr != null) {
				// logger.debug("record found " + attr.get());
				// System.out.println("record found " + attr.get());
			}
		}
		ctx.close();

		return true;
	} catch (Exception e) {
		System.out.println("LDAP error search: ");
		// logger.error(e, e);
		e.printStackTrace();
		return false;
	}
}
 
Example 7
Source File: LdapIdentityProviderSession.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected GroupEntity transformGroup(SearchResult result) throws NamingException {
  final Attributes attributes = result.getAttributes();
  LdapGroupEntity group = new LdapGroupEntity();
  group.setDn(result.getNameInNamespace());
  group.setId(getStringAttributeValue(ldapConfiguration.getGroupIdAttribute(), attributes));
  group.setName(getStringAttributeValue(ldapConfiguration.getGroupNameAttribute(), attributes));
  group.setType(getStringAttributeValue(ldapConfiguration.getGroupTypeAttribute(), attributes));
  return group;
}
 
Example 8
Source File: LdapUserGroupBuilder.java    From ranger with Apache License 2.0 5 votes vote down vote up
private void getRootDN() throws Throwable {
	NamingEnumeration groupSearchResultEnum = null;
	SearchControls sc1 = new SearchControls();
	sc1.setSearchScope(SearchControls.OBJECT_SCOPE);
	sc1.setReturningAttributes(new String[]{"namingContexts"});
	try {
		createLdapContext();
		groupSearchResultEnum = ldapContext
				.search("", "objectclass=*", sc1);
		//System.out.println("goUpGroupHierarchyLdap(): Going through the sub groups");
		while (groupSearchResultEnum.hasMore()) {
			SearchResult result1 = (SearchResult) groupSearchResultEnum.next();

			Attributes attrs = result1.getAttributes();
			Attribute attr = attrs.get("namingContexts");
			if (LOG.isDebugEnabled()) {
				LOG.debug("namingContexts = " + attr);
			}
			groupSearchBase = new String[] {attr.get(0).toString()};
			LOG.info("RootDN = " + Arrays.toString(groupSearchBase));
		}
	} catch (RuntimeException re) {
		throw re;
	} finally {
		if (groupSearchResultEnum != null) {
			groupSearchResultEnum.close();
		}
		closeLdapContext();
	}
}
 
Example 9
Source File: LdapIdentityProviderSession.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected LdapUserEntity transformUser(SearchResult result) throws NamingException {
  final Attributes attributes = result.getAttributes();
  LdapUserEntity user = new LdapUserEntity();
  user.setDn(result.getNameInNamespace());
  user.setId(getStringAttributeValue(ldapConfiguration.getUserIdAttribute(), attributes));
  user.setFirstName(getStringAttributeValue(ldapConfiguration.getUserFirstnameAttribute(), attributes));
  user.setLastName(getStringAttributeValue(ldapConfiguration.getUserLastnameAttribute(), attributes));
  user.setEmail(getStringAttributeValue(ldapConfiguration.getUserEmailAttribute(), attributes));
  return user;
}
 
Example 10
Source File: LdapSearch.java    From cxf with Apache License 2.0 5 votes vote down vote up
public Attributes findAttributes(String rootDN, String filter) throws NamingException {
    NamingEnumeration<SearchResult> answer = searchSubTree(rootDN, filter);
    if (answer.hasMore()) {
        SearchResult sr = answer.next();
        return sr.getAttributes();
    }
    return null;
}
 
Example 11
Source File: LDAPIdentityStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Set<LDAPCapabilityRepresentation> queryServerCapabilities() {
    Set<LDAPCapabilityRepresentation> result = new LinkedHashSet<>();
    try {
        List<String> attrs = new ArrayList<>();
        attrs.add("supportedControl");
        attrs.add("supportedExtension");
        attrs.add("supportedFeatures");
        List<SearchResult> searchResults = operationManager
            .search("", "(objectClass=*)", Collections.unmodifiableCollection(attrs), SearchControls.OBJECT_SCOPE);
        if (searchResults.size() != 1) {
            throw new ModelException("Could not query root DSE: unexpected result size");
        }
        SearchResult rootDse = searchResults.get(0);
        Attributes attributes = rootDse.getAttributes();
        for (String attr: attrs) {
            Attribute attribute = attributes.get(attr);
            if (null != attribute) {
                CapabilityType capabilityType = CapabilityType.fromRootDseAttributeName(attr);
                NamingEnumeration<?> values = attribute.getAll();
                while (values.hasMoreElements()) {
                    Object o = values.nextElement();
                    LDAPCapabilityRepresentation capability = new LDAPCapabilityRepresentation(o, capabilityType);
                    logger.info("rootDSE query: " + capability);
                    result.add(capability);
                }
            }
        }
        return result;
    } catch (NamingException e) {
        throw new ModelException("Failed to query root DSE: " + e.getMessage(), e);
    }
}
 
Example 12
Source File: LdapUserService.java    From pmq with Apache License 2.0 5 votes vote down vote up
private void doInitUser(Map<String, UserInfo> userInfos, Map<String, Organization> orgMap, String serverPath)
		throws NamingException {
	Properties env = new Properties();
	env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
	env.put(Context.SECURITY_AUTHENTICATION, "simple");
	env.put(Context.SECURITY_PRINCIPAL, "corp\\" + soaConfig.getMqLdapUser());
	env.put(Context.SECURITY_CREDENTIALS, soaConfig.getMqLdapPass());
	env.put(Context.PROVIDER_URL, adServer.get());

	LdapContext ctx = new InitialLdapContext(env, null);
	SearchControls searchCtls = new SearchControls();
	searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

	String searchFilter = String
			.format("(&(objectClass=top)(objectClass=user)(objectClass=person)(objectClass=organizationalPerson))");

	String returnedAtts[] = { "memberOf", "sAMAccountName", "cn", "distinguishedName", "mail" };
	searchCtls.setReturningAttributes(returnedAtts);
	NamingEnumeration<SearchResult> answer = ctx.search(serverPath, searchFilter, searchCtls);
	while (answer.hasMoreElements()) {
		SearchResult sr = (SearchResult) answer.next();
		Attributes at = sr.getAttributes();
		UserInfo userInfo = new UserInfo();
		userInfo.setDepartment(getDValue(at.get("distinguishedName")));
		userInfo.setEmail(getValue(at.get("mail")));
		userInfo.setUserId(getValue(at.get("sAMAccountName")));
		userInfo.setName(getValue(at.get("cn")));
		userInfo.setAdmin(roleService.isAdmin(userInfo.getUserId()));
		userInfos.put(userInfo.getUserId(), userInfo);
		if (!StringUtils.isEmpty(userInfo.getDepartment())) {
			Organization organization = new Organization();
			organization.setOrgId(userInfo.getDepartment());
			orgMap.put(userInfo.getDepartment(), organization);
		}
	}
	ctx.close();
}
 
Example 13
Source File: LDAPDataDao.java    From boubei-tss with Apache License 2.0 4 votes vote down vote up
public List<?> getOtherUsers(Map<String, String> paramsMap, String attributes, String groupId, Object...otherParams) {
    String filterString =  otherParams.length > 0 ? (String)otherParams[0] : USER_FILTER_STR;
    
    Document doc = XMLDocUtil.dataXml2Doc(attributes);
    Map<String, String> fieldNames = new HashMap<String, String>();
    Map<String, String> defaultValues = new HashMap<String, String>();
    
    for (Iterator<?> it = doc.getRootElement().elementIterator(); it.hasNext();) {
        Element element = (Element) it.next();
        fieldNames.put(element.getName(), element.getText());
        defaultValues.put(element.getName(), element.attribute(DEFAULT_VALUE).getText());
    }
    
    List<UserDTO> items = new ArrayList<UserDTO>();
    Set<String> loginNameSet = new HashSet<String> ();
    Set<String> dnCache = new HashSet<String> ();
    // 数据查询
    try {
    	DirContext conn =  getConnection(paramsMap);
        NamingEnumeration<SearchResult> en = ldapSearch(conn, groupId, filterString);         
        while (en != null && en.hasMoreElements()) {
            SearchResult sr = en.next();
            String dn = sr.getName();
            
            // 组合全路径
            dn = dn + "," + groupId;
            if(dnCache.contains(dn)) continue;
            
            Attributes attrs = sr.getAttributes();
            
            if (attrs.get(SN_TAG) == null){
                continue;
            }
            
            UserDTO user = new UserDTO();
            user.setId(dn);
            user.setGroupId(getGroupId(dn));                
            user.setUserName( getNameValueFromAttribute( attrs, SN_TAG ) );
            
            // 获得用户的属性              
            // loginName
            String uid_in_ldap = getNameValueFromAttribute(attrs, fieldNames.get(LOGIN_NAME_USER));
            if (uid_in_ldap != null) { // uid简称 有可能重名,重名只导入第一个
                if(loginNameSet.contains(uid_in_ldap)) {
                    continue;
                }
                user.setLoginName(uid_in_ldap);
            } 
            else {
                user.setLoginName(dn);
            }
            
            // email
            String emailName = fieldNames.get(EAMIL_USER);
            String emailValue = getValueFromAttribute(attrs, emailName);
            user.setEmail(emailValue);
 
            // sex
            String sexName = fieldNames.get(SEX_USER);
        	String sexValue = getValueFromAttribute(attrs, sexName);
        	user.setSex(sexValue);


            // telephone
String telephoneName = fieldNames.get(TELE_PHONE);
String telephoneValue = getValueFromAttribute(attrs, telephoneName);
        	user.setTelephone(telephoneValue);

            // employeeNo
String employeeNoName = fieldNames.get(EMPLOYEE_NO_USER);
            user.setEmployeeNo(defaultValues.get(employeeNoName));
            
            // disabled
            String disabled = fieldNames.get(USER_STATUS);
            user.setAuthMethod(defaultValues.get(disabled));
            
            items.add(user);
            dnCache.add(dn);
            loginNameSet.add(user.getLoginName());
        }
    } catch (NamingException e) {           
        throw new BusinessException("获取外部用户失败!",e);
    }
    return items;
}
 
Example 14
Source File: LDAPUserRegistry.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
private NodeDescription mapToNode(Map<String, String> attributeMapping, Map<String, String> attributeDefaults,
        SearchResult result) throws NamingException
{
    NodeDescription nodeDescription = new NodeDescription(result.getNameInNamespace());
    Attributes ldapAttributes = result.getAttributes();

    // Parse the timestamp
    Attribute modifyTimestamp = ldapAttributes.get(this.modifyTimestampAttributeName);
    if (modifyTimestamp != null)
    {
        try
        {
            nodeDescription.setLastModified(this.timestampFormat.parse(modifyTimestamp.get().toString()));
        }
        catch (ParseException e)
        {
            throw new AlfrescoRuntimeException("Failed to parse timestamp.", e);
        }
    }

    // Apply the mapped attributes
    PropertyMap properties = nodeDescription.getProperties();
    for (String key : attributeMapping.keySet())
    {
        QName keyQName = QName.createQName(key, this.namespaceService);

        // cater for null
        String attributeName = attributeMapping.get(key);
        if (attributeName != null)
        {
            Attribute attribute = ldapAttributes.get(attributeName);
            String defaultAttribute = attributeDefaults.get(key);
            
            if (attribute != null)
            {
                String value = (String) attribute.get(0);
                if (value != null)
                {
                    properties.put(keyQName, value);
                }
            }
            else if (defaultAttribute != null)
            {
                properties.put(keyQName, defaultAttribute);
            }
            else
            {
                // Make sure that a 2nd sync, updates deleted ldap attributes(MNT-14026)
                properties.put(keyQName, null);
            }
        }
        else
        {
            String defaultValue = attributeDefaults.get(key);
            if (defaultValue != null)
            {
                properties.put(keyQName, defaultValue);
            }
        }
    }
    return nodeDescription;
}
 
Example 15
Source File: UserSync.java    From ranger with Apache License 2.0 4 votes vote down vote up
public void getAllGroups(LdapContext ldapContext) throws Throwable {
    int noOfGroups = 0;
    Attribute groupNameAttr;
    Attribute groupMemberAttr;
    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    SearchControls groupSearchControls = new SearchControls();
    groupSearchControls.setSearchScope(config.getGroupSearchScope());
    Set<String> groupSearchAttributes = new HashSet<>();
    groupSearchAttributes.add(groupNameAttrName);
    groupSearchAttributes.add(groupMemberName);
    groupSearchAttributes.add("distinguishedName");
    groupSearchControls.setReturningAttributes(groupSearchAttributes.toArray(
            new String[groupSearchAttributes.size()]));

    String extendedGroupSearchFilter= "(objectclass=" + groupObjClassName + ")";
    if (groupSearchFilter != null && !groupSearchFilter.trim().isEmpty()) {
        String customFilter = groupSearchFilter.trim();
        if (!customFilter.startsWith("(")) {
            customFilter = "(" + customFilter + ")";
        }
        extendedGroupSearchFilter = "(&" + extendedGroupSearchFilter + customFilter + ")";
    }

    try {

        groupSearchResultEnum = ldapContext.search(groupSearchBase, extendedGroupSearchFilter,
                groupSearchControls);

        logFile.println("\nINFO: First 20 Groups and associated Users are:");

        while (groupSearchResultEnum.hasMore()) {
            final SearchResult groupEntry = groupSearchResultEnum.next();
            if (groupEntry == null) {
                continue;
            }
            Attributes groupAttributes = groupEntry.getAttributes();
            if (groupAttributes == null) {
                logFile.println("WARN: Attributes missing for entry " + groupEntry.getNameInNamespace());
                continue;
            }

            groupMemberAttr = groupAttributes.get(groupMemberName);

            Set<String> users = new HashSet<>();
            if (groupMemberAttr != null) {
                NamingEnumeration<?> userEnum = groupMemberAttr.getAll();
                while (userEnum.hasMore()) {
                    String userRes = userEnum.next().toString();
                    users.add(userRes);
                }
            }

            groupNameAttr = groupAttributes.get(groupNameAttrName);
            if (noOfGroups < 20) {
                logFile.println("Group name: " + groupNameAttr.get().toString() + ", Users: " + users);
            }
            noOfGroups++;
        }

        logFile.println("\nINFO: Total no. of groups = " + noOfGroups);

    } catch (NamingException ne) {
        String msg = "Exception occured while retreiving groups\n";
        if ((config.getGroupNameAttribute() != null && !config.getGroupNameAttribute().isEmpty()) ||
                (config.getGroupObjectClass() != null && !config.getGroupObjectClass().isEmpty()) ||
                (config.getUserGroupMemberAttributeName() != null && !config.getUserGroupMemberAttributeName().isEmpty()) ||
                (config.getGroupSearchBase() != null && !config.getGroupSearchBase().isEmpty()) ||
                (config.getGroupSearchFilter() != null && !config.getGroupSearchFilter().isEmpty())) {
            throw new Exception("Please verify values for:\n ranger.usersync.group.memberattributename\n " +
                    "ranger.usersync.group.nameattribute\n" +
                    "ranger.usersync.group.objectclass\n" +
                    "ranger.usersync.group.searchbase\n" +
                    "ranger.usersync.group.searchfilter\n");
        } else {
            throw new Exception(msg + ne);
        }
    } finally {

        if (groupSearchResultEnum != null) {
            groupSearchResultEnum.close();
        }
    }
}
 
Example 16
Source File: LdapCallbackHandler.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 @param ctx - the context to search from
 @param user - the input username
 @param credential - the bind credential
 @param baseDN - base DN to search the ctx from
 @param filter - the search filter string
 @return the userDN string for the successful authentication
 @throws NamingException
 */
@SuppressWarnings("rawtypes")
protected String bindDNAuthentication(InitialLdapContext ctx, String user, Object credential, String baseDN,
      String filter) throws NamingException
{
   SearchControls constraints = new SearchControls();
   constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
   constraints.setTimeLimit(searchTimeLimit);
   String attrList[] = {distinguishedNameAttribute};
   constraints.setReturningAttributes(attrList);

   NamingEnumeration results = null;

   Object[] filterArgs = {user};
   results = ctx.search(baseDN, filter, filterArgs, constraints);
   if (results.hasMore() == false)
   {
      results.close();
      throw PicketBoxMessages.MESSAGES.failedToFindBaseContextDN(baseDN);
   }

   SearchResult sr = (SearchResult) results.next();
   String name = sr.getName();
   String userDN = null;
   Attributes attrs = sr.getAttributes();
   if (attrs != null)
   {
       Attribute dn = attrs.get(distinguishedNameAttribute);
       if (dn != null)
       {
               userDN = (String) dn.get();
       }
   }
   if (userDN == null)
   {
       if (sr.isRelative() == true)
           userDN = name + ("".equals(baseDN) ? "" : "," + baseDN);
       else
           throw PicketBoxMessages.MESSAGES.unableToFollowReferralForAuth(name);
   }

   safeClose(results);
   results = null;

   InitialLdapContext userCtx = constructInitialLdapContext(userDN, credential);
   safeClose(userCtx);

   return userDN;
}
 
Example 17
Source File: LdapUtil.java    From jeecg with Apache License 2.0 4 votes vote down vote up
/**
 * @param base
 *            :根节点(在这里是"dc=example,dc=com")
 * @param scope
 *            :搜索范围,分为"base"(本节点),"one"(单层),""(遍历)
 * @param filter
 *            :指定子节点(格式为"(objectclass=*)",*是指全部,你也可以指定某一特定类型的树节点)
 */
public void searchInformation(String base, String scope, String filter,
		DirContext dc) {
	SearchControls sc = new SearchControls();
	if (scope.equals("base")) {
		sc.setSearchScope(SearchControls.OBJECT_SCOPE);
	} else if (scope.equals("one")) {
		sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
	} else {
		sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
	}
	NamingEnumeration<?> ne = null;
	try {
		ne = dc.search(base, filter, sc);
		// Use the NamingEnumeration object to cycle through
		// the result set.
		while (ne.hasMore()) {
			//System.out.println();
			SearchResult sr = (SearchResult) ne.next();
			String name = sr.getName();
			if (base != null && !base.equals("")) {
				LogUtil.info("entry: " + name + "," + base);
			} else {
				LogUtil.info("entry: " + name);
			}

			Attributes at = sr.getAttributes();
			NamingEnumeration<?> ane = at.getAll();
			while (ane.hasMore()) {
				Attribute attr = (Attribute) ane.next();
				String attrType = attr.getID();
				NamingEnumeration<?> values = attr.getAll();
				// Another NamingEnumeration object, this time
				// to iterate through attribute values.
				while (values.hasMore()) {
					Object oneVal = values.nextElement();
					if (oneVal instanceof String) {
						LogUtil.info(attrType + ": "+ (String) oneVal);
					} else {
						LogUtil.info(attrType + ": "+ new String((byte[]) oneVal));
					}
				}
			}
		}
	} catch (Exception nex) {
		System.err.println("Error: " + nex.getMessage());
		nex.printStackTrace();
	}
}
 
Example 18
Source File: UserSync.java    From ranger with Apache License 2.0 4 votes vote down vote up
private void findBasicGroupProperties(LdapContext ldapContext) throws Throwable {
    int noOfGroups;
    Attribute groupNameAttr;
    String groupBase;
    String groupFilter;
    Attribute groupMemberAttr;
    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    SearchControls groupSearchControls = new SearchControls();
    groupSearchControls.setSearchScope(config.getGroupSearchScope());

    try {
 if (groupName == null || groupName.isEmpty()) {
 	groupSearchResultEnum = ldapContext.search(searchBase, null);
 } else {
            int baseIndex = groupName.indexOf(",");
        	groupBase = groupName.substring(baseIndex + 1);
        	groupFilter = groupName.substring(0, baseIndex);
        	groupSearchResultEnum = ldapContext.search(groupBase, groupFilter,
                groupSearchControls);
 }
        noOfGroups = 0;
        while (groupSearchResultEnum.hasMore()) {
            if (noOfGroups >= 1) {
                break;
            }

            final SearchResult groupEntry = groupSearchResultEnum.next();
            if (groupEntry == null) {
                continue;
            }
            Attributes groupAttributes = groupEntry.getAttributes();
            if (groupAttributes == null) {
                logFile.println("WARN: Attributes missing for entry " + groupEntry.getNameInNamespace());
                continue;
            }

            Attribute groupObjClassAttr = groupAttributes.get("objectClass");
            if (groupObjClassAttr != null) {
                NamingEnumeration<?> groupObjClassEnum = groupObjClassAttr.getAll();
                while (groupObjClassEnum.hasMore()) {
                    String groupObjClassStr = groupObjClassEnum.next().toString();
                    for (int i = 0; i < groupObjectClassValues.length; i++) {
                        if (groupObjClassStr.equalsIgnoreCase(groupObjectClassValues[i])) {
                            groupObjClassName = groupObjClassStr;
                            break;
                        }
                    }
                }
            } else {
                logFile.println("WARN: Failed to find group objectClass attribute for " + groupEntry.getNameInNamespace());
                continue;
            }

            if (groupNameAttrName == null || groupNameAttrName.isEmpty()) {

                for (int i = 0; i < groupNameAttrValues.length; i++) {
                    groupNameAttr = groupAttributes.get(groupNameAttrValues[i]);
                    if (groupNameAttr != null) {
                        groupNameAttrName = groupNameAttrValues[i];
                        break;
                    }
                }
            }

            for (int i = 0; i < groupMemAttrValues.length; i++) {
                groupMemberAttr = groupAttributes.get(groupMemAttrValues[i]);
                if (groupMemberAttr != null) {
                    groupMemberName = groupMemAttrValues[i];
                    break;
                }
            }
            noOfGroups++;
        }

        installProps.println("\n# Possible values for group search related properties:");
        installProps.println("SYNC_GROUP_MEMBER_ATTRIBUTE_NAME=" + groupMemberName);
        installProps.println("SYNC_GROUP_NAME_ATTRIBUTE=" + groupNameAttrName);
        installProps.println("SYNC_GROUP_OBJECT_CLASS=" + groupObjClassName);

        ambariProps.println("\n# Possible values for group search related properties:");
        ambariProps.println("ranger.usersync.group.memberattributename=" + groupMemberName);
        ambariProps.println("ranger.usersync.group.nameattribute=" + groupNameAttrName);
        ambariProps.println("ranger.usersync.group.objectclass=" + groupObjClassName);

    } finally {

        if (groupSearchResultEnum != null) {
            groupSearchResultEnum.close();
        }
    }
}
 
Example 19
Source File: ActiveDirectoryGroupRealm.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext)
        throws NamingException {
  Set<String> roleNames = new LinkedHashSet<>();

  SearchControls searchCtls = new SearchControls();
  searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
  String userPrincipalName = username;
  if (this.principalSuffix != null && userPrincipalName.indexOf('@') > 1) {
    userPrincipalName = userPrincipalName.split("@")[0];
  }

  String searchFilter = String.format("(&(objectClass=*)(%s=%s))", this.getUserSearchAttributeName(), userPrincipalName);
  Object[] searchArguments = new Object[]{userPrincipalName};

  NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments,
      searchCtls);

  while (answer.hasMoreElements()) {
    SearchResult sr = (SearchResult) answer.next();

    if (log.isDebugEnabled()) {
      log.debug("Retrieving group names for user [" + sr.getName() + "]");
    }

    Attributes attrs = sr.getAttributes();

    if (attrs != null) {
      NamingEnumeration ae = attrs.getAll();
      while (ae.hasMore()) {
        Attribute attr = (Attribute) ae.next();

        if (attr.getID().equals("memberOf")) {

          Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);

          if (log.isDebugEnabled()) {
            log.debug("Groups found for user [" + username + "]: " + groupNames);
          }

          Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
          roleNames.addAll(rolesForGroups);
        }
      }
    }
  }
  return roleNames;
}
 
Example 20
Source File: UserSync.java    From ranger with Apache License 2.0 4 votes vote down vote up
private void findAdvGroupProperties(LdapContext ldapContext) throws Throwable {
    int noOfGroups = 0;
    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    SearchControls groupSearchControls = new SearchControls();
    groupSearchControls.setSearchScope(config.getGroupSearchScope());
    Set<String> groupSearchAttributes = new HashSet<>();
    groupSearchAttributes.add(groupNameAttrName);
    groupSearchAttributes.add(groupMemberName);
    groupSearchAttributes.add("distinguishedName");
    groupSearchControls.setReturningAttributes(groupSearchAttributes.toArray(
            new String[groupSearchAttributes.size()]));
    String extendedGroupSearchFilter = "(objectclass=" + groupObjClassName + ")";

    try {
        HashMap<String, Integer> ouOccurences = new HashMap<>();
        if (groupSearchBase == null || groupSearchBase.isEmpty()) {
        	groupSearchResultEnum = ldapContext.search(searchBase, extendedGroupSearchFilter,
                groupSearchControls);
        } else {
        	groupSearchResultEnum = ldapContext.search(groupSearchBase, extendedGroupSearchFilter,
                    groupSearchControls);
        }

        while (groupSearchResultEnum.hasMore()) {
            if (noOfGroups >= 20) {
                break;
            }

            final SearchResult groupEntry = groupSearchResultEnum.next();
            if (groupEntry == null) {
                continue;
            }
            Attributes groupAttributes = groupEntry.getAttributes();
            if (groupAttributes == null) {
                logFile.println("WARN: Attributes missing for entry " + groupEntry.getNameInNamespace());
                continue;
            }

            String dnValue;

            Attribute dnAttr = groupAttributes.get("distinguishedName");
            if (dnAttr != null) {
                dnValue = dnAttr.get().toString();
                String ouStr = "OU=";
                int indexOfOU = dnValue.indexOf(ouStr);
                if (indexOfOU > 0) {
                    dnValue = dnValue.substring(indexOfOU);

                } else {
                    dnValue = dnValue.substring(dnValue.indexOf(",") + 1);
                }

            } else {
                // If distinguishedName is not found,
                // strip off the userName from the long name for OU or sub domain
                dnValue = groupEntry.getNameInNamespace();
                dnValue = dnValue.substring(dnValue.indexOf(",") + 1);
            }
            //System.out.println("OU from dn = " + dnValue);
            Integer ouOccrs = ouOccurences.get(dnValue);
            if (ouOccrs == null) {
                //System.out.println("value = 0");
                ouOccrs = Integer.valueOf(0);
            }
            int val = ouOccrs.intValue();
            ouOccrs = Integer.valueOf(++val);
            ouOccurences.put(dnValue, ouOccrs);

            noOfGroups++;
        }

        if (!ouOccurences.isEmpty()) {
            Set<String> keys = ouOccurences.keySet();
            int maxOUOccr = 0;
            for (String key : keys) {
                int ouOccurVal = ouOccurences.get(key).intValue();
                logFile.println("INFO: No. of groups from " + key + " = " + ouOccurVal);
                if (ouOccurVal > maxOUOccr) {
                    maxOUOccr = ouOccurVal;
                    groupSearchBase = key;
                }
            }
        }

        if (groupSearchFilter == null || groupSearchFilter.isEmpty()) {
        	groupSearchFilter = groupNameAttrName + "=*";
        }

        installProps.println("SYNC_GROUP_SEARCH_BASE=" + groupSearchBase);
        installProps.println("SYNC_LDAP_GROUP_SEARCH_FILTER=" + groupSearchFilter);

        ambariProps.println("ranger.usersync.group.searchbase=" + groupSearchBase);
        ambariProps.println("ranger.usersync.group.searchfilter=" + groupSearchFilter);

    } finally {

        if (groupSearchResultEnum != null) {
            groupSearchResultEnum.close();
        }
    }
}