Java Code Examples for org.springframework.ldap.support.LdapUtils#convertLdapException()

The following examples show how to use org.springframework.ldap.support.LdapUtils#convertLdapException() . 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: LdapSearchContext.java    From hesperides with GNU General Public License v3.0 6 votes vote down vote up
private DirContext buildSearchContext(String username, String password) {
    Hashtable<String, String> env = new Hashtable<>();
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapConfiguration.getUrl());
    env.put(Context.OBJECT_FACTORIES, DefaultDirObjectFactory.class.getName());
    env.put("com.sun.jndi.ldap.connect.timeout", ldapConfiguration.getConnectTimeout());
    env.put("com.sun.jndi.ldap.read.timeout", ldapConfiguration.getReadTimeout());
    env.put(Context.SECURITY_PRINCIPAL, String.format("%s\\%s", ldapConfiguration.getDomain(), username));
    env.put(Context.SECURITY_CREDENTIALS, password);

    try {
        DirContext dirContext = new InitialLdapContext(env, null);
        // ici dirContext ne contient que des infos relatives au serveur avec lequel la connexion vient d'être établie
        if (log.isDebugEnabled()) { // on évite ce traitement si ce n'est pas nécessaire
            log.debug("[buildSearchContext] dirContext: {}", gson.toJson(attributesToNative(dirContext.getAttributes("").getAll())));
        }
        return dirContext;
    } catch (AuthenticationException | OperationNotSupportedException cause) {
        throw new BadCredentialsException(messages.getMessage(
                "LdapAuthenticationProvider.badCredentials", "Bad credentials"), cause);
    } catch (NamingException e) {
        log.error(e.getExplanation() + (e.getCause() != null ? (" : " + e.getCause().getMessage()) : ""));
        throw LdapUtils.convertLdapException(e);
    }
}
 
Example 2
Source File: LdapAuthenticationProvider.java    From hesperides with GNU General Public License v3.0 6 votes vote down vote up
private Set<String> extractGroupAuthoritiesRecursivelyWithCache(DirContextAdapter userData, String username, String password) {
    Attributes attributes;
    try {
        attributes = userData.getAttributes("");
    } catch (NamingException e) {
        throw LdapUtils.convertLdapException(e);
    }
    LdapSearchContext ldapSearchContext = createLdapSearchContext(username, password);
    try {
        cachedParentLdapGroupAuthorityRetriever.setParentGroupsDNRetriever(ldapSearchContext);
        Set<String> groupAuthorities = new HashSet<>();
        HashSet<String> parentGroupsDN = extractDirectParentGroupDNs(attributes);
        for (String groupDN : parentGroupsDN) {
            groupAuthorities.addAll(cachedParentLdapGroupAuthorityRetriever.retrieveParentGroups(groupDN));
        }
        return groupAuthorities;
    } finally {
        ldapSearchContext.closeContext();
    }
}
 
Example 3
Source File: VirtualListViewControlDirContextProcessor.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
protected void handleResponse(Object control)
{
    byte[] result = (byte[]) invokeMethod("getContextID",
            responseControlClass, control);
    Integer listSize = (Integer) invokeMethod("getListSize",
            responseControlClass, control);
    Integer targetOffset = (Integer) invokeMethod(
            "getTargetOffset", responseControlClass, control);
    this.exception = (NamingException) invokeMethod("getException",
            responseControlClass, control);

    this.cookie = new VirtualListViewResultsCookie(result,
            targetOffset.intValue(), listSize.intValue());

    if (exception != null) {
        throw LdapUtils.convertLdapException(exception);
    }
}
 
Example 4
Source File: NameAwareAttribute.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a new instance from the supplied Attribute.
 *
 * @param attribute the Attribute to copy.
 */
public NameAwareAttribute(Attribute attribute) {
    this(attribute.getID(), attribute.isOrdered());
    try {
        NamingEnumeration<?> incomingValues = attribute.getAll();
        while(incomingValues.hasMore()) {
            this.add(incomingValues.next());
        }
    } catch (NamingException e) {
        throw LdapUtils.convertLdapException(e);
    }

    if (attribute instanceof NameAwareAttribute) {
        NameAwareAttribute nameAwareAttribute = (NameAwareAttribute) attribute;
        populateValuesAsNames(nameAwareAttribute, this);
    }
}
 
Example 5
Source File: AbstractContextSource.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
private DirContext doGetContext(String principal, String credentials, boolean explicitlyDisablePooling) {
    Hashtable<String, Object> env = getAuthenticatedEnv(principal, credentials);
    if(explicitlyDisablePooling) {
        env.remove(SUN_LDAP_POOLING_FLAG);
    }

    DirContext ctx = createContext(env);

    try {
        DirContext processedDirContext = authenticationStrategy.processContextAfterCreation(ctx, principal, credentials);
        return processedDirContext;
    }
    catch (NamingException e) {
        closeContext(ctx);
        throw LdapUtils.convertLdapException(e);
    }
}
 
Example 6
Source File: AbstractContextSource.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
/**
 * Create a DirContext using the supplied environment.
 *
 * @param environment the LDAP environment to use when creating the
 * <code>DirContext</code>.
 * @return a new DirContext implementation initialized with the supplied
 * environment.
 */
protected DirContext createContext(Hashtable<String, Object> environment) {
	DirContext ctx = null;

	try {
		ctx = getDirContextInstance(environment);

		if (LOG.isInfoEnabled()) {
			Hashtable<?, ?> ctxEnv = ctx.getEnvironment();
			String ldapUrl = (String) ctxEnv.get(Context.PROVIDER_URL);
			LOG.debug("Got Ldap context on server '" + ldapUrl + "'");
		}

		return ctx;
	}
	catch (NamingException e) {
		closeContext(ctx);
		throw LdapUtils.convertLdapException(e);
	}
}
 
Example 7
Source File: DirContextAdapter.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
    * {@inheritDoc}
    */
   @Override
public void update() {
	NamingEnumeration<? extends Attribute> attributesEnumeration = null;

	try {
		attributesEnumeration = updatedAttrs.getAll();

		// find what to update
		while (attributesEnumeration.hasMore()) {
			Attribute a = attributesEnumeration.next();

			// if it does not exist it should be added
			if (isEmptyAttribute(a)) {
				originalAttrs.remove(a.getID());
			}
			else {
				// Otherwise it should be set.
				originalAttrs.put(a);
			}
		}
	}
	catch (NamingException e) {
		throw LdapUtils.convertLdapException(e);
	}
	finally {
		closeNamingEnumeration(attributesEnumeration);
	}

	// Reset the attributes to be updated
	updatedAttrs = new NameAwareAttributes();
}
 
Example 8
Source File: DirContextAdapter.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
    * {@inheritDoc}
    */
   @Override
public Object getObjectAttribute(String name) {
	Attribute oneAttr = originalAttrs.get(name);
	if (oneAttr == null || oneAttr.size() == 0) { // LDAP-215
		return null;
	}
	try {
		return oneAttr.get();
	}
	catch (NamingException e) {
		throw LdapUtils.convertLdapException(e);
	}
}
 
Example 9
Source File: DirContextAdapter.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
    * {@inheritDoc}
    */
   @Override
public ModificationItem[] getModificationItems() {
	if (!updateMode) {
		return new ModificationItem[0];
	}

	List<ModificationItem> tmpList = new LinkedList<ModificationItem>();
	NamingEnumeration<? extends Attribute> attributesEnumeration = null;
	try {
		attributesEnumeration = updatedAttrs.getAll();

		// find attributes that have been changed, removed or added
		while (attributesEnumeration.hasMore()) {
			NameAwareAttribute oneAttr = (NameAwareAttribute) attributesEnumeration.next();

			collectModifications(oneAttr, tmpList);
		}
	}
	catch (NamingException e) {
		throw LdapUtils.convertLdapException(e);
	}
	finally {
		closeNamingEnumeration(attributesEnumeration);
	}

	if (log.isDebugEnabled()) {
		log.debug("Number of modifications:" + tmpList.size());
	}

	return tmpList.toArray(new ModificationItem[tmpList.size()]);
}
 
Example 10
Source File: DirContextAdapter.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
    * {@inheritDoc}
    */
   @Override
public String[] getNamesOfModifiedAttributes() {

	List<String> tmpList = new ArrayList<String>();

	NamingEnumeration<? extends Attribute> attributesEnumeration;
	if (isUpdateMode()) {
		attributesEnumeration = updatedAttrs.getAll();
	}
	else {
		attributesEnumeration = originalAttrs.getAll();
	}

	try {
		while (attributesEnumeration.hasMore()) {
			Attribute oneAttribute = attributesEnumeration
					.next();
			tmpList.add(oneAttribute.getID());
		}
	}
	catch (NamingException e) {
		throw LdapUtils.convertLdapException(e);
	}
	finally {
		closeNamingEnumeration(attributesEnumeration);
	}

	return tmpList.toArray(new String[tmpList.size()]);
}
 
Example 11
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
       * {@inheritDoc}
       */
public T getObjectFromNameClassPair(NameClassPair nameClassPair) {
	try {
		return mapper.mapFromNameClassPair(nameClassPair);
	}
	catch (javax.naming.NamingException e) {
		throw LdapUtils.convertLdapException(e);
	}
}
 
Example 12
Source File: LdapTemplate.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
private <T> T executeWithContext(ContextExecutor<T> ce, DirContext ctx) {
	try {
		return ce.executeWithContext(ctx);
	}
	catch (javax.naming.NamingException e) {
		throw LdapUtils.convertLdapException(e);
	}
	finally {
		closeContext(ctx);
	}
}
 
Example 13
Source File: LookupAttemptingCallback.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Override
public DirContextOperations mapWithContext(DirContext ctx, LdapEntryIdentification ldapEntryIdentification) {
    try {
        return (DirContextOperations) ctx.lookup(ldapEntryIdentification.getRelativeName());
    }
    catch (NamingException e) {
        // rethrow, because we aren't allowed to throw checked exceptions.
        throw LdapUtils.convertLdapException(e);
    }
}
 
Example 14
Source File: AttributesMapperCallbackHandler.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * Cast the NameClassPair to a SearchResult and pass its attributes to the
 * {@link AttributesMapper}.
 * 
 * @param nameClassPair a <code> SearchResult</code> instance.
 * @return the Object returned from the mapper.
 */
public T getObjectFromNameClassPair(NameClassPair nameClassPair) {
	if (!(nameClassPair instanceof SearchResult)) {
		throw new IllegalArgumentException("Parameter must be an instance of SearchResult");
	}

	SearchResult searchResult = (SearchResult) nameClassPair;
	Attributes attributes = searchResult.getAttributes();
	try {
		return mapper.mapFromAttributes(attributes);
	}
	catch (javax.naming.NamingException e) {
		throw LdapUtils.convertLdapException(e);
	}
}
 
Example 15
Source File: LdapAuthenticationProvider.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
public HashSet<String> getUserGroupsDN(String username, String password) {
    DirContextAdapter dirContextAdapter = (DirContextAdapter) self.searchCN(username, password);
    Attributes attributes;
    try {
        attributes = dirContextAdapter.getAttributes("");
    } catch (NamingException e) {
        throw LdapUtils.convertLdapException(e);
    } finally {
        LdapUtils.closeContext(dirContextAdapter);
    }
    return extractDirectParentGroupDNs(attributes);
}
 
Example 16
Source File: LdapSearchContext.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
public static HashSet<String> extractDirectParentGroupDNs(Attributes attributes) {
    try {
        Attribute memberOf = attributes.get("memberOf");
        HashSet<String> groupsDNs = new HashSet<>();
        if (memberOf != null) {
            for (int i = 0; i < memberOf.size(); i++) {
                groupsDNs.add((String) memberOf.get(i));
            }
        }
        return groupsDNs;
    } catch (NamingException e) {
        throw LdapUtils.convertLdapException(e);
    }
}
 
Example 17
Source File: LdapSearchContext.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
private static DirContextOperations searchCN(DirContext dirContext, String cn, String base, String searchFilter) {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    try {
        // Durant cet appel, SpringSecurityLdapTemplate logue parfois des "Ignoring PartialResultException"
        return SpringSecurityLdapTemplate.searchForSingleEntryInternal(dirContext, searchControls, base, searchFilter, new Object[]{cn});
    } catch (NamingException exception) {
        throw LdapUtils.convertLdapException(exception);
    }
}
 
Example 18
Source File: LdapSearchContext.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
public HashSet<String> retrieveParentGroupDNs(String dn) {
    HashSet<String> parentGroupDNs = new HashSet<>();
    try {
        String cn = DirectoryGroupDN.extractCnFromDn(dn);
        String base = getBaseFrom(cn, dn);
        String searchFilter = ldapConfiguration.getSearchFilterForCN(cn);
        DirContextOperations dirContextOperations = searchCNWithRetry(cn, base, searchFilter);
        parentGroupDNs = extractDirectParentGroupDNs(dirContextOperations.getAttributes(""));
    } catch (IncorrectResultSizeDataAccessException e) {
        // On accepte que la recherche ne retourne aucun résultat
    } catch (NamingException exception) {
        throw LdapUtils.convertLdapException(exception);
    }
    return parentGroupDNs;
}
 
Example 19
Source File: AbstractContextSource.java    From spring-ldap with Apache License 2.0 3 votes vote down vote up
/**
 * Default implementation of setting the environment up to be authenticated.
 * This method should typically NOT be overridden; any customization to the
 * authentication mechanism should be managed by setting a different
 * {@link DirContextAuthenticationStrategy} on this instance.
 *
 * @param env the environment to modify.
 * @param principal the principal to authenticate with.
 * @param credentials the credentials to authenticate with.
 * @see DirContextAuthenticationStrategy
 * @see #setAuthenticationStrategy(DirContextAuthenticationStrategy)
 */
protected void setupAuthenticatedEnvironment(Hashtable<String, Object> env, String principal, String credentials) {
	try {
		authenticationStrategy.setupEnvironment(env, principal, credentials);
	}
	catch (NamingException e) {
		throw LdapUtils.convertLdapException(e);
	}
}