Search in sources :

Example 26 with Attribute

use of javax.naming.directory.Attribute in project adempiere by adempiere.

the class LDAP method dump.

/**
	 * 	Test NT
	 *	@throws LoginException
	 *
	private static void testNT () throws LoginException
	{
		try
		{
			System.out.println ("NT system ----------------------------");
			NTSystem ntsystem = new NTSystem ();
			System.out.println (ntsystem);
			System.out.println (ntsystem.getDomain ());
			System.out.println (ntsystem.getDomainSID ());
			System.out.println (ntsystem.getName ());
			System.out.println (ntsystem.getUserSID ());
			System.out.println ("NT login ----------------------------");
			NTLoginModule ntlogin = new NTLoginModule ();
			System.out.println (ntlogin);
			Map<String,String> map = new HashMap<String,String>();
			map.put ("debug", "true");
			ntlogin.initialize (null, null, null, map);
			System.out.println (ntlogin.login ());
		}
		catch (LoginException le)
		{
			System.err.println ("Authentication attempt failed" + le);
		}
	} //	testNT
	
	
	/**
	 * 	testKerberos
	 *	@throws LoginException
	 *
	private static void testKerberos ()
		throws LoginException
	{
		System.out.println ("Krb login ----------------------------");
		Map<String,String> map = new HashMap<String,String>();
		// map.put("debug", "true");
		// map.put("debugNative", "true");
		Krb5LoginModule klogin = new Krb5LoginModule ();
		System.out.println (klogin);
		map.put ("principal", "username@compiere.org");
		map.put ("credential", "pass");
		klogin.initialize (null, null, null, map);
		System.out.println (klogin.login ());
		/***********************************************************************
		 * ** No krb5.ini file found in entire system Debug is true storeKey
		 * false useTicketCache false useKeyTab false doNotPrompt false
		 * ticketCache is null KeyTab is null refreshKrb5Config is false
		 * principal is jjanke tryFirstPass is false useFirstPass is false
		 * storePass is false clearPass is false [Krb5LoginModule]
		 * authentication failed Could not load configuration file
		 * c:\winnt\krb5.ini (The system cannot find the file specified)
		 * javax.security.auth.login.LoginException: Could not load
		 * configuration file c:\winnt\krb5.ini (The system cannot find the file
		 * specified)
		 *
	} //	testKerbos
	/**/
/**
	 * 	Print Attributes to System.out
	 *	@param attrs
	 */
private static void dump(Attributes attrs) {
    if (attrs == null) {
        System.out.println("No attributes");
    } else {
        /* Print each attribute */
        try {
            for (NamingEnumeration<? extends Attribute> ae = attrs.getAll(); ae.hasMore(); ) {
                Attribute attr = ae.next();
                System.out.println("attribute: " + attr.getID());
                /* print each value */
                for (NamingEnumeration<?> e = attr.getAll(); e.hasMore(); System.out.println("    value: " + e.next())) ;
            }
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }
}
Also used : Attribute(javax.naming.directory.Attribute) NamingException(javax.naming.NamingException)

Example 27 with Attribute

use of javax.naming.directory.Attribute in project jackrabbit-oak by apache.

the class InternalLdapServer method addMembers.

public void addMembers(String groupDN, Iterable<String> memberDNs) throws Exception {
    LdapContext ctxt = getWiredContext();
    Attribute attr = new BasicAttribute("member");
    for (String dn : memberDNs) {
        attr.add(dn);
    }
    BasicAttributes attrs = new BasicAttributes();
    attrs.put(attr);
    ctxt.modifyAttributes(groupDN, DirContext.ADD_ATTRIBUTE, attrs);
}
Also used : BasicAttribute(javax.naming.directory.BasicAttribute) BasicAttributes(javax.naming.directory.BasicAttributes) BasicAttribute(javax.naming.directory.BasicAttribute) Attribute(javax.naming.directory.Attribute) LdapContext(javax.naming.ldap.LdapContext)

Example 28 with Attribute

use of javax.naming.directory.Attribute in project cloudstack by apache.

the class OpenLdapUserManagerImpl method getUsersInGroup.

@Override
public List<LdapUser> getUsersInGroup(String groupName, LdapContext context) throws NamingException {
    String attributeName = _ldapConfiguration.getGroupUniqueMemeberAttribute();
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(_ldapConfiguration.getScope());
    controls.setReturningAttributes(new String[] { attributeName });
    NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(), generateGroupSearchFilter(groupName), controls);
    final List<LdapUser> users = new ArrayList<LdapUser>();
    //Expecting only one result which has all the users
    if (result.hasMoreElements()) {
        Attribute attribute = result.nextElement().getAttributes().get(attributeName);
        NamingEnumeration<?> values = attribute.getAll();
        while (values.hasMoreElements()) {
            String userdn = String.valueOf(values.nextElement());
            try {
                users.add(getUserForDn(userdn, context));
            } catch (NamingException e) {
                s_logger.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage());
            }
        }
    }
    Collections.sort(users);
    return users;
}
Also used : Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException)

Example 29 with Attribute

use of javax.naming.directory.Attribute in project spring-security by spring-projects.

the class JndiDnsResolver method resolveServiceEntry.

// This method is needed, so that we can use only one DirContext for
// resolveServiceIpAddress().
private String resolveServiceEntry(String serviceType, String domain, DirContext ctx) {
    String result = null;
    try {
        String query = new StringBuilder("_").append(serviceType).append("._tcp.").append(domain).toString();
        Attribute dnsRecord = lookup(query, ctx, "SRV");
        // There are maybe more records defined, we will return the one
        // with the highest priority (lowest number) and the highest weight
        // (highest number)
        int highestPriority = -1;
        int highestWeight = -1;
        for (NamingEnumeration<?> recordEnum = dnsRecord.getAll(); recordEnum.hasMoreElements(); ) {
            String[] record = recordEnum.next().toString().split(" ");
            if (record.length != 4) {
                throw new DnsLookupException("Wrong service record for query " + query + ": [" + Arrays.toString(record) + "]");
            }
            int priority = Integer.parseInt(record[0]);
            int weight = Integer.parseInt(record[1]);
            // we have a new highest Priority, so forget also the highest weight
            if (priority < highestPriority || highestPriority == -1) {
                highestPriority = priority;
                highestWeight = weight;
                result = record[3].trim();
            }
            // same priority, but higher weight
            if (priority == highestPriority && weight > highestWeight) {
                highestWeight = weight;
                result = record[3].trim();
            }
        }
    } catch (NamingException e) {
        throw new DnsLookupException("DNS lookup failed for service " + serviceType + " at " + domain, e);
    }
    // remove the "." at the end
    if (result.endsWith(".")) {
        result = result.substring(0, result.length() - 1);
    }
    return result;
}
Also used : Attribute(javax.naming.directory.Attribute) NamingException(javax.naming.NamingException)

Example 30 with Attribute

use of javax.naming.directory.Attribute in project ranger by apache.

the class LdapDeltaUserGroupBuilder method getGroups.

private void getGroups(UserGroupSink sink) throws Throwable {
    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
    long highestdeltaSyncGroupTime = deltaSyncGroupTime;
    try {
        createLdapContext();
        int total;
        // Activate paged results
        if (pagedResultsEnabled) {
            ldapContext.setRequestControls(new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) });
        }
        extendedGroupSearchFilter = "(objectclass=" + groupObjectClass + ")";
        if (groupSearchFilter != null && !groupSearchFilter.trim().isEmpty()) {
            String customFilter = groupSearchFilter.trim();
            if (!customFilter.startsWith("(")) {
                customFilter = "(" + customFilter + ")";
            }
            extendedGroupSearchFilter = extendedGroupSearchFilter + customFilter;
        }
        extendedAllGroupsSearchFilter = "(&" + extendedGroupSearchFilter + "(|(uSNChanged>=" + deltaSyncGroupTime + ")(modifyTimestamp>=" + deltaSyncGroupTimeStamp + "Z)))";
        LOG.info("extendedAllGroupsSearchFilter = " + extendedAllGroupsSearchFilter);
        for (int ou = 0; ou < groupSearchBase.length; ou++) {
            byte[] cookie = null;
            int counter = 0;
            try {
                int paged = 0;
                do {
                    groupSearchResultEnum = ldapContext.search(groupSearchBase[ou], extendedAllGroupsSearchFilter, groupSearchControls);
                    while (groupSearchResultEnum.hasMore()) {
                        final SearchResult groupEntry = groupSearchResultEnum.next();
                        if (groupEntry == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info("groupEntry null, skipping sync for the entry");
                            }
                            continue;
                        }
                        counter++;
                        noOfGroups++;
                        Attribute groupNameAttr = groupEntry.getAttributes().get(groupNameAttribute);
                        if (groupNameAttr == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info(groupNameAttribute + " empty for entry " + groupEntry.getNameInNamespace() + ", skipping sync");
                            }
                            continue;
                        }
                        String gName = (String) groupNameAttr.get();
                        String transformGroupName = groupNameTransform(gName);
                        // check for group members and populate userInfo object with user's full name and group mapping
                        if (groupSearchFirstEnabled) {
                            LOG.debug("Update Ranger admin with " + transformGroupName);
                            sink.addOrUpdateGroup(transformGroupName);
                        }
                        Attribute timeStampAttr = groupEntry.getAttributes().get("uSNChanged");
                        if (timeStampAttr != null) {
                            String uSNChangedVal = (String) timeStampAttr.get();
                            long currentDeltaSyncTime = Long.parseLong(uSNChangedVal);
                            if (currentDeltaSyncTime > highestdeltaSyncGroupTime) {
                                highestdeltaSyncGroupTime = currentDeltaSyncTime;
                            }
                        } else {
                            timeStampAttr = groupEntry.getAttributes().get("modifytimestamp");
                            if (timeStampAttr != null) {
                                String timeStampVal = (String) timeStampAttr.get();
                                Date parseDate = dateFormat.parse(timeStampVal);
                                long currentDeltaSyncTime = parseDate.getTime();
                                LOG.info("timeStampVal = " + timeStampVal + "and currentDeltaSyncTime = " + currentDeltaSyncTime);
                                if (currentDeltaSyncTime > highestdeltaSyncGroupTime) {
                                    highestdeltaSyncGroupTime = currentDeltaSyncTime;
                                    deltaSyncGroupTimeStamp = timeStampVal;
                                }
                            }
                        }
                        Attribute groupMemberAttr = groupEntry.getAttributes().get(groupMemberAttributeName);
                        int userCount = 0;
                        if (groupMemberAttr == null || groupMemberAttr.size() <= 0) {
                            LOG.info("No members available for " + gName);
                            continue;
                        }
                        NamingEnumeration<?> userEnum = groupMemberAttr.getAll();
                        while (userEnum.hasMore()) {
                            String originalUserFullName = (String) userEnum.next();
                            if (originalUserFullName == null || originalUserFullName.trim().isEmpty()) {
                                continue;
                            }
                            userCount++;
                            String userName = getShortUserName(originalUserFullName);
                            originalUserFullName = originalUserFullName.toLowerCase();
                            if (groupSearchFirstEnabled && !userSearchEnabled) {
                                String transformUserName = userNameTransform(userName);
                                try {
                                    sink.addOrUpdateUser(transformUserName);
                                } catch (Throwable t) {
                                    LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage() + ", for user: " + transformUserName);
                                }
                                userNameMap.put(originalUserFullName, transformUserName);
                                noOfUsers++;
                            }
                            // System.out.println("Adding " + userNameMap.get(originalUserFullName) + " and fullname = " + originalUserFullName + " to " + gName);
                            if (userNameMap.get(originalUserFullName) != null) {
                                groupUserTable.put(gName, originalUserFullName, userNameMap.get(originalUserFullName));
                            } else {
                                groupUserTable.put(gName, originalUserFullName, originalUserFullName);
                            }
                            groupNameMap.put(groupEntry.getNameInNamespace().toLowerCase(), gName);
                        }
                        LOG.info("No. of members in the group " + gName + " = " + userCount);
                    }
                    // Examine the paged results control response
                    Control[] controls = ldapContext.getResponseControls();
                    if (controls != null) {
                        for (int i = 0; i < controls.length; i++) {
                            if (controls[i] instanceof PagedResultsResponseControl) {
                                PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                                total = prrc.getResultSize();
                                if (total != 0) {
                                    LOG.debug("END-OF-PAGE total : " + total);
                                } else {
                                    LOG.debug("END-OF-PAGE total : unknown");
                                }
                                cookie = prrc.getCookie();
                            }
                        }
                    } else {
                        LOG.debug("No controls were sent from the server");
                    }
                    // Re-activate paged results
                    if (pagedResultsEnabled) {
                        LOG.debug(String.format("Fetched paged results round: %s", ++paged));
                        ldapContext.setRequestControls(new Control[] { new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) });
                    }
                } while (cookie != null);
                LOG.info("LdapDeltaUserGroupBuilder.getGroups() completed with group count: " + counter);
            } catch (Exception t) {
                LOG.error("LdapDeltaUserGroupBuilder.getGroups() failed with exception: " + t);
                LOG.info("LdapDeltaUserGroupBuilder.getGroups() group count: " + counter);
            }
        }
    } finally {
        if (groupSearchResultEnum != null) {
            groupSearchResultEnum.close();
        }
        closeLdapContext();
    }
    if (groupHierarchyLevels > 0) {
        LOG.debug("deltaSyncGroupTime = " + deltaSyncGroupTime);
        if (deltaSyncGroupTime > 0) {
            LOG.info("LdapDeltaUserGroupBuilder.getGroups(): Going through group hierarchy for nested group evaluation for deltasync");
            goUpGroupHierarchyLdap(groupNameMap.keySet(), groupHierarchyLevels - 1);
        }
    }
    if (deltaSyncGroupTime < highestdeltaSyncGroupTime) {
        // Incrementing highestdeltaSyncGroupTime (for AD) in order to avoid search record repetition for next sync cycle.
        deltaSyncGroupTime = highestdeltaSyncGroupTime + 1;
        // Incrementing the highest timestamp value (for OpenLdap) with 1min in order to avoid search record repetition for next sync cycle.
        deltaSyncGroupTimeStamp = dateFormat.format(new Date(highestdeltaSyncGroupTime + 60000l));
    }
}
Also used : Attribute(javax.naming.directory.Attribute) PagedResultsResponseControl(javax.naming.ldap.PagedResultsResponseControl) SearchResult(javax.naming.directory.SearchResult) Date(java.util.Date) InvalidNameException(javax.naming.InvalidNameException) Control(javax.naming.ldap.Control) PagedResultsControl(javax.naming.ldap.PagedResultsControl) PagedResultsResponseControl(javax.naming.ldap.PagedResultsResponseControl) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) SimpleDateFormat(java.text.SimpleDateFormat) PagedResultsControl(javax.naming.ldap.PagedResultsControl)

Aggregations

Attribute (javax.naming.directory.Attribute)288 Attributes (javax.naming.directory.Attributes)162 NamingException (javax.naming.NamingException)133 BasicAttribute (javax.naming.directory.BasicAttribute)97 SearchResult (javax.naming.directory.SearchResult)92 ArrayList (java.util.ArrayList)74 BasicAttributes (javax.naming.directory.BasicAttributes)64 NamingEnumeration (javax.naming.NamingEnumeration)56 SearchControls (javax.naming.directory.SearchControls)55 DirContext (javax.naming.directory.DirContext)46 InitialDirContext (javax.naming.directory.InitialDirContext)40 HashSet (java.util.HashSet)38 HashMap (java.util.HashMap)29 IOException (java.io.IOException)24 LdapName (javax.naming.ldap.LdapName)20 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)18 Hashtable (java.util.Hashtable)17 Map (java.util.Map)17 ModificationItem (javax.naming.directory.ModificationItem)17 List (java.util.List)15