Java Code Examples for javax.naming.NamingEnumeration#close()

The following examples show how to use javax.naming.NamingEnumeration#close() . 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 presto with Apache License 2.0 6 votes vote down vote up
private void checkGroupMembership(String user, String contextUserDistinguishedName, String contextPassword)
        throws NamingException
{
    DirContext context = createUserDirContext(contextUserDistinguishedName, contextPassword);
    try {
        NamingEnumeration<SearchResult> search = searchGroupMembership(user, context);
        try {
            if (!search.hasMore()) {
                String message = format("User [%s] not a member of an authorized group", user);
                log.debug(message);
                throw new AccessDeniedException(message);
            }
        }
        finally {
            search.close();
        }
    }
    finally {
        context.close();
    }
}
 
Example 2
Source File: LdapUtil.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
private static String getUid (String username) throws Exception {
    DirContext ctx = ldapContext();
    String filter = String.format(config.searchFilter, username);
    SearchControls ctrl = new SearchControls();
    ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration answer = ctx.search(config.searchBase, filter, ctrl);

    String dn;
    if (answer.hasMore()) {
        SearchResult result = (SearchResult) answer.next();
        dn = result.getNameInNamespace();
    }
    else {
        dn = null;
    }
    answer.close();
    return dn;
}
 
Example 3
Source File: DirContextAdapter.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
private void closeNamingEnumeration(NamingEnumeration<?> enumeration) {
	try {
		if (enumeration != null) {
			enumeration.close();
		}
	}
	catch (NamingException e) {
		// Never mind this
	}
}
 
Example 4
Source File: JNDIRealm.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Add values of a specified attribute to a list
 *
 * @param attrId Attribute name
 * @param attrs Attributes containing the new values
 * @param values ArrayList containing values found so far
 * @return the list of attribute values
 * @exception NamingException if a directory server error occurs
 */
private ArrayList<String> addAttributeValues(String attrId,
                                     Attributes attrs,
                                     ArrayList<String> values)
    throws NamingException{

    if (containerLog.isTraceEnabled())
        containerLog.trace("  retrieving values for attribute " + attrId);
    if (attrId == null || attrs == null)
        return values;
    if (values == null)
        values = new ArrayList<>();
    Attribute attr = attrs.get(attrId);
    if (attr == null)
        return values;
    NamingEnumeration<?> e = attr.getAll();
    try {
        while(e.hasMore()) {
            String value = (String)e.next();
            values.add(value);
        }
    } catch (PartialResultException ex) {
        if (!adCompat)
            throw ex;
    } finally {
        e.close();
    }
    return values;
}
 
Example 5
Source File: LdapAuthenticator.java    From presto with Apache License 2.0 5 votes vote down vote up
private String validateGroupMembership(String user, DirContext context)
        throws NamingException
{
    NamingEnumeration<SearchResult> search = searchGroupMembership(user, context);
    try {
        if (!search.hasMore()) {
            String message = format("User [%s] not a member of an authorized group", user);
            log.debug(message);
            throw new AccessDeniedException(message);
        }

        String userDistinguishedName = search.next().getNameInNamespace();
        while (search.hasMore()) {
            String nextUserDistinguishedName = search.next().getNameInNamespace();
            if (!userDistinguishedName.equals(nextUserDistinguishedName)) {
                log.debug("Multiple group membership results for user [%s] with different distinguished names: [%s], [%s]", user, userDistinguishedName, nextUserDistinguishedName);
                throw new AccessDeniedException(format("Multiple group membership results for user [%s] with different distinguished names", user));
            }
        }

        log.debug("Group membership validated for user [%s]", user);
        return userDistinguishedName;
    }
    finally {
        search.close();
    }
}
 
Example 6
Source File: JndiResourceResolverFactory.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private static void closeThenThrow(NamingEnumeration<?> namingEnumeration, NamingException e)
    throws NamingException {
  try {
    namingEnumeration.close();
  } catch (NamingException ignored) {
    // ignore
  }
  throw e;
}
 
Example 7
Source File: LdapConnectionWrapper.java    From Alpine with Apache License 2.0 5 votes vote down vote up
/**
 * Closes a NamingEnumeration object without throwing any exceptions.
 * @param object the NamingEnumeration object to close
 * @since 1.4.0
 */
public void closeQuietly(final NamingEnumeration object) {
    try {
        if (object != null) {
            object.close();
        }
    } catch (final NamingException e) {
        // ignore
    }
}
 
Example 8
Source File: LdapClient.java    From iaf with Apache License 2.0 5 votes vote down vote up
public String getFirstSearchResult(NamingEnumeration<SearchResult> searchResultEnum) throws NamingException {
  	String result=null;
  	try {
   	if (searchResultEnum.hasMore()) {
   		result=getFirstAttribute(searchResultEnum.next());
   	}
} catch(PartialResultException e) {
	if (log.isDebugEnabled()) log.debug("ignoring Exception: "+e); 
} finally {
	searchResultEnum.close();
}
return result;
  }
 
Example 9
Source File: LdapCallbackHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
protected void safeClose(NamingEnumeration results)
{
	if(results != null)
	{
		try
		{
			results.close();
		} catch (NamingException e) {}
	}
}
 
Example 10
Source File: JNDIConfiguration.java    From commons-configuration with Apache License 2.0 4 votes vote down vote up
/**
 * This method recursive traverse the JNDI tree, looking for Context objects.
 * When it finds them, it traverses them as well.  Otherwise it just adds the
 * values to the list of keys found.
 *
 * @param keys All the keys that have been found.
 * @param context The parent context
 * @param prefix What prefix we are building on.
 * @param processedCtx a set with the so far processed objects
 * @throws NamingException If JNDI has an issue.
 */
private void recursiveGetKeys(final Set<String> keys, final Context context, final String prefix,
        final Set<Context> processedCtx) throws NamingException
{
    processedCtx.add(context);
    NamingEnumeration<NameClassPair> elements = null;

    try
    {
        elements = context.list("");

        // iterates through the context's elements
        while (elements.hasMore())
        {
            final NameClassPair nameClassPair = elements.next();
            final String name = nameClassPair.getName();
            final Object object = context.lookup(name);

            // build the key
            final StringBuilder key = new StringBuilder();
            key.append(prefix);
            if (key.length() > 0)
            {
                key.append(".");
            }
            key.append(name);

            if (object instanceof Context)
            {
                // add the keys of the sub context
                final Context subcontext = (Context) object;
                if (!processedCtx.contains(subcontext))
                {
                    recursiveGetKeys(keys, subcontext, key.toString(),
                            processedCtx);
                }
            }
            else
            {
                // add the key
                keys.add(key.toString());
            }
        }
    }
    finally
    {
        // close the enumeration
        if (elements != null)
        {
            elements.close();
        }
    }
}
 
Example 11
Source File: OpenLdapDirectoryProvider.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
protected boolean userExists(String id)
{
	env.put(Context.SECURITY_AUTHENTICATION, "simple");
	env.put(Context.SECURITY_CREDENTIALS, "secret");

	try
	{
		DirContext ctx = new InitialDirContext(env);

		/*
		 * Setup subtree scope to tell LDAP to recursively descend directory structure during searches.
		 */
		SearchControls searchControls = new SearchControls();
		searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

		/*
		 * Setup the directory entry attributes we want to search for. In this case it is the user's ID.
		 */

		String filter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(id) + "))";

		/* Execute the search, starting at the directory level of Users */

		NamingEnumeration hits = ctx.search(getBasePath(), filter, searchControls);

		/* All we need to know is if there were any hits at all. */

		if (hits.hasMore())
		{
			hits.close();
			ctx.close();
			return true;
		}
		else
		{
			hits.close();
			ctx.close();
			return false;
		}
	}
	catch (Exception e)
	{
		log.error(e.getMessage(), e);
		return false;
	}
}
 
Example 12
Source File: LdapRolesMappingProvider.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
protected void rolesSearch(InitialLdapContext ctx, SearchControls constraints, String user, String previousRoleDn,
                           int recursionMax, int nesting, RoleGroup roleGroup) throws NamingException
{
   Object[] filterArgs = {user};
   String searchFilter = previousRoleDn == null ? roleFilter : "member=" + previousRoleDn;
   NamingEnumeration<SearchResult> results = ctx.search(rolesCtxDN, searchFilter, filterArgs, constraints);
   try
   {
      while (results.hasMore())
      {
         SearchResult sr = results.next();
         String dn = canonicalize(sr.getName());

         // Query the context for the roleDN values
         String[] attrNames = {roleAttributeID};
         Attributes result = ctx.getAttributes(dn, attrNames);
         if (result != null && result.size() > 0)
         {
            Attribute roles = result.get(roleAttributeID);
            for (int n = 0; n < roles.size(); n++)
            {
               String roleName = (String) roles.get(n);
               if (roleAttributeIsDN && parseRoleNameFromDN)
               {
                  parseRole(roleName, roleGroup);
               }
               else if (roleAttributeIsDN)
               {
                  // Query the roleDN location for the value of roleNameAttributeID
                  String roleDN = roleName;
                  String[] returnAttribute = {roleNameAttributeID};
                  PicketBoxLogger.LOGGER.traceFollowRoleDN(roleDN);
                  try
                  {
                     Attributes result2 = ctx.getAttributes(roleDN, returnAttribute);
                     Attribute roles2 = result2.get(roleNameAttributeID);
                     if (roles2 != null)
                     {
                        for (int m = 0; m < roles2.size(); m++)
                        {
                           roleName = (String) roles2.get(m);
                           addRole(roleName, roleGroup);
                        }
                     }
                  }
                  catch (NamingException e)
                  {
                     PicketBoxLogger.LOGGER.debugFailureToQueryLDAPAttribute(roleNameAttributeID, roleDN, e);
                  }
               }
               else
               {
                  // The role attribute value is the role name
                  addRole(roleName, roleGroup);
               }
            }
         }

         if (nesting < recursionMax)
         {
            rolesSearch(ctx, constraints, user, dn, recursionMax, nesting + 1, roleGroup);
         }
      }
   }
   finally
   {
      if (results != null)
         results.close();
   }
}
 
Example 13
Source File: TestLdap.java    From davmail with GNU General Public License v2.0 4 votes vote down vote up
public void testSearchByGalfindUnsupportedAttribute() throws NamingException {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    NamingEnumeration<SearchResult> searchResults = ldapContext.search("ou=people", "(postalcode=N18 1ZF)", searchControls);
    searchResults.close();
}
 
Example 14
Source File: LdapAccessControl.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
@Override
public boolean hasRole(final String username, final String attribute) {
    final String key = username + "_attr_" + attribute;
    final long now = System.currentTimeMillis();

    try {
        if (!matchedExpired(key, now)) {
            return true;
        }

        if (!unMatchedExpired(key, now)) {
            return false;
        }

        // query AD to update both MapS and expiration time
        LOGGER.fine("username: " + username + "; role: " + attribute);

        this.writeLock.lock();
        try {
            // remove from cache if exists
            this.matchedList.remove(key);
            this.unMatchedList.remove(key);

            int count = 0;
            final LdapContext context = new InitialLdapContext(environment, null);
            for (String filter : this.policy) {
                // perform AD lookup add to cache 
                final NamingEnumeration<SearchResult> results =
                        context.search(this.deecee
                                , String.format(filter, username, attribute)
                                , this.srchCntrls);

                final boolean found = results.hasMoreElements();
                results.close();

                // add to cache
                if (found) {
                    count++;
                    //LOGGER.info("add attribute to matchedList: " + attribute);
                    this.matchedList.put(key, System.currentTimeMillis());
                    if (!this.uniqueOnly) {
                        break;
                    }
                }

                // check if we have a duplicate attribute
                if (count > 1 && this.uniqueOnly) {
                    this.matchedList.remove(key);
                    throw new IllegalArgumentException("Uniqueness property violated. "
                            + "Found duplicate role/attribute:" + attribute
                            + ". This MAY be caused by an improper policy definition"
                            + "; filter=" + filter
                            + "; policy=" + this.policy);
                }
            }
            context.close();

            if (0 == count) {
                //LOGGER.info("add attribute to unMatchedList: " + attribute);
                this.unMatchedList.put(key, System.currentTimeMillis());
            } else {
                cacheUserInfo(username);
            }

        } finally {
            this.writeLock.unlock();
        }
    } catch (NamingException lex) {
        LOGGER.severe(lex.getMessage());
        throw new RuntimeException(lex);
    }

    return hasRole(username, attribute);
}
 
Example 15
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 16
Source File: LdapManager.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Check if the given DN matches the group search filter
 *
 * @param dn the absolute DN of the node to check
 * @return true if the given DN is matching the group filter. false oterwise.
 * @throws NamingException if the search for the dn fails.
 */
public boolean isGroupDN(LdapName dn) throws NamingException {
    Log.debug("LdapManager: Trying to check if DN is a group. DN: {}, Base DN: {} ...", dn, baseDN);

    // is it a sub DN of the base DN?
    if (!dn.startsWith(baseDN)
        && (alternateBaseDN == null || !dn.startsWith(alternateBaseDN))) {
        if (Log.isDebugEnabled()) {
            Log.debug("LdapManager: DN ({}) does not fit to baseDN ({},{})", dn, baseDN, alternateBaseDN);
        }
        return false;
    }

    DirContext ctx = null;
    try {
        Log.debug("LdapManager: Starting LDAP search to check group DN: {}", dn);
        // Search for the group in the node with the given DN.
        // should return the group object itself if is matches the group filter
        ctx = getContext(dn);
        // only search the object itself.
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.OBJECT_SCOPE);
        constraints.setReturningAttributes(new String[]{});
        String filter = MessageFormat.format(getGroupSearchFilter(), "*");
        NamingEnumeration<SearchResult> answer = ctx.search("", filter, constraints);

        Log.debug("LdapManager: ... group check search finished for DN: {}", dn);

        boolean result = (answer != null && answer.hasMoreElements());

        if (answer != null) {
            answer.close();
        }
        Log.debug("LdapManager: DN is group: {}? {}!", dn, result);
        return result;
    }
    catch (final Exception e) {
        Log.debug("LdapManager: Exception thrown when checking if DN is a group {}", dn, e);
        throw e;
    }
    finally {
        try {
            if (ctx != null)
                ctx.close();
        }
        catch (Exception ex) {
            Log.debug("An exception occurred while trying to close a LDAP context after trying to verify that DN '{}' is a group.", dn, ex);
        }
    }
}
 
Example 17
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 18
Source File: LdapRealm.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
boolean isUserMemberOfDynamicGroup(LdapName userLdapDn, String memberUrl,
    final LdapContextFactory ldapContextFactory) throws NamingException {
  // ldap://host:port/dn?attributes?scope?filter?extensions
  if (memberUrl == null) {
    return false;
  }
  String[] tokens = memberUrl.split("\\?");
  if (tokens.length < 4) {
    return false;
  }

  String searchBaseString = tokens[0].substring(tokens[0].lastIndexOf("/") + 1);
  String searchScope = tokens[2];
  String searchFilter = tokens[3];

  LdapName searchBaseDn = new LdapName(searchBaseString);

  // do scope test
  if ("base".equalsIgnoreCase(searchScope)) {
    log.debug("DynamicGroup SearchScope base");
    return false;
  }
  if (!userLdapDn.toString().endsWith(searchBaseDn.toString())) {
    return false;
  }
  if ("one".equalsIgnoreCase(searchScope) && (userLdapDn.size() != searchBaseDn.size() - 1)) {
    log.debug("DynamicGroup SearchScope one");
    return false;
  }
  // search for the filter, substituting base with userDn
  // search for base_dn=userDn, scope=base, filter=filter
  LdapContext systemLdapCtx = null;
  systemLdapCtx = ldapContextFactory.getSystemLdapContext();
  boolean member = false;
  NamingEnumeration<SearchResult> searchResultEnum = null;
  try {
    searchResultEnum = systemLdapCtx.search(userLdapDn, searchFilter,
                                            "sub".equalsIgnoreCase(searchScope) ? SUBTREE_SCOPE : ONELEVEL_SCOPE);
    if (searchResultEnum.hasMore()) {
      return true;
    }
  } finally {
    try {
      if (searchResultEnum != null) {
        searchResultEnum.close();
      }
    } finally {
      LdapUtils.closeContext(systemLdapCtx);
    }
  }
  return member;
}
 
Example 19
Source File: CtrlAuthentication.java    From linstor-server with GNU General Public License v3.0 4 votes vote down vote up
private AccessContext signInLDAP(IdentityName idName, byte[] password)
    throws SignInException
{
    AccessContext signInContext = null;

    Hashtable<String, String> ldapEnv = new Hashtable<>();
    ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    ldapEnv.put(Context.PROVIDER_URL, ctrlCfg.getLdapUri());
    ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
    String ldapDN = ctrlCfg.getLdapDn().replaceAll("\\{user}", idName.displayValue);
    ldapEnv.put(Context.SECURITY_PRINCIPAL, ldapDN);
    ldapEnv.put(Context.SECURITY_CREDENTIALS, new String(password, StandardCharsets.UTF_8));

    try
    {
        DirContext ctx = new InitialDirContext(ldapEnv);

        if (!ctrlCfg.getLdapSearchFilter().isEmpty())
        {
            SearchControls searchControls = new SearchControls();
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            final String searchFilter = ctrlCfg.getLdapSearchFilter().replaceAll("\\{user}", idName.displayValue);

            NamingEnumeration result = ctx.search(ctrlCfg.getLdapSearchFilter(), searchFilter, searchControls);

            if (!result.hasMore())
            {
                result.close();
                throw new InvalidCredentialsException(
                    "Sign-in failed: LDAP search filter didn't find a match.",
                    // Description
                    "Sign-in failed",
                    // Cause
                    "Search filter expression didn't match any item.",
                    // Correction
                    "Adapt LDAP search_base,search_filter or add user to searched group.",
                    // No error details
                    null
                );
            }

            result.close();
        }

        signInContext = publicCtx;
        errorLog.logInfo("LDAP User %s successfully authenticated.", idName.displayValue);
    }
    catch (NamingException nExc)
    {
        throw new InvalidCredentialsException(
            "Sign-in failed: Invalid sign in credentials",
            // Description
            "Sign-in failed",
            // Cause
            "The credentials for the sign-in are not valid or LDAP access not correctly configured.",
            // Correction
            "The name of a valid identity and a matching password must be provided " +
                "to sign in to the system or LDAP access correctly configured.",
            nExc.getMessage(),
            nExc
        );
    }
    return signInContext;
}
 
Example 20
Source File: KnoxLdapRealm.java    From knox with Apache License 2.0 4 votes vote down vote up
boolean isUserMemberOfDynamicGroup(LdapName userLdapDn, String memberUrl,
    final LdapContextFactory ldapContextFactory) throws NamingException {

  // ldap://host:port/dn?attributes?scope?filter?extensions

  boolean member = false;

  if (memberUrl == null) {
    return false;
  }
  String[] tokens = memberUrl.split("\\?");
  if (tokens.length < 4) {
    return false;
  }

  String searchBaseString = tokens[0]
      .substring(tokens[0].lastIndexOf('/') + 1);
  String searchScope = tokens[2];
  String searchFilter = tokens[3];

  LdapName searchBaseDn = new LdapName(searchBaseString);

  // do scope test
  if ("base".equalsIgnoreCase(searchScope)) {
    return false;
  }
  if (!userLdapDn.toString().endsWith(searchBaseDn.toString())) {
    return false;
  }
  if ("one".equalsIgnoreCase(searchScope)
      && (userLdapDn.size() != searchBaseDn.size() - 1)) {
    return false;
  }
  // search for the filter, substituting base with userDn
  // search for base_dn=userDn, scope=base, filter=filter
  LdapContext systemLdapCtx;
  systemLdapCtx = ldapContextFactory.getSystemLdapContext();
  NamingEnumeration<SearchResult> searchResultEnum = null;
  try {
    searchResultEnum = systemLdapCtx
      .search(userLdapDn, searchFilter,
          "sub".equalsIgnoreCase(searchScope) ? SUBTREE_SCOPE
              : ONELEVEL_SCOPE);
    if (searchResultEnum.hasMore()) {
      return true;
    }
  }
  finally {
      try {
        if (searchResultEnum != null) {
          searchResultEnum.close();
        }
      }
      finally {
        LdapUtils.closeContext(systemLdapCtx);
      }
  }
  return member;
}