Search in sources :

Example 36 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project ldapchai by ldapchai.

the class JNDIProviderImpl method generateNewJndiContext.

private static LdapContext generateNewJndiContext(final Hashtable environment) throws ChaiOperationException, ChaiUnavailableException {
    final String url = String.valueOf(environment.get(Context.PROVIDER_URL));
    final String bindDN = String.valueOf(environment.get(Context.SECURITY_PRINCIPAL));
    try {
        final long startTime = System.currentTimeMillis();
        final LdapContext newDirContext;
        newDirContext = new InitialLdapContext(environment, null);
        LOGGER.trace("bind successful as " + bindDN + " (" + (System.currentTimeMillis() - startTime) + "ms)");
        return newDirContext;
    } catch (NamingException e) {
        final StringBuilder logMsg = new StringBuilder();
        logMsg.append("unable to bind to ");
        logMsg.append(url);
        logMsg.append(" as ");
        logMsg.append(bindDN);
        logMsg.append(" reason: ");
        if (e instanceof CommunicationException) {
            logMsg.append("CommunicationException (").append(e.getMessage());
            final Throwable rootCause = e.getRootCause();
            if (rootCause != null) {
                logMsg.append("; ").append(rootCause.getMessage());
            }
            logMsg.append(")");
            throw new ChaiUnavailableException(logMsg.toString(), ChaiError.COMMUNICATION, false, true);
        } else {
            logMsg.append(e.getMessage());
            // check for bad password or intruder detection
            throw ChaiUnavailableException.forErrorMessage(logMsg.toString());
        }
    }
}
Also used : ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) CommunicationException(javax.naming.CommunicationException) InitialLdapContext(javax.naming.ldap.InitialLdapContext) NamingException(javax.naming.NamingException) InitialLdapContext(javax.naming.ldap.InitialLdapContext) LdapContext(javax.naming.ldap.LdapContext)

Example 37 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project ART-TIME by Artezio.

the class LdapAdapter method listEmployees.

private List<Employee> listEmployees(Filter filter) {
    List<Employee> employees = new ArrayList<Employee>();
    InitialLdapContext ctx = null;
    try {
        ctx = initializeContext();
        SearchControls controls = makeSearchControls();
        NamingEnumeration<SearchResult> answer = ctx.search(getUserContextDN(), filter.getExpression(), filter.getArgs(), controls);
        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            Attributes attrs = sr.getAttributes();
            Employee employee;
            employee = createEmployee(attrs);
            employees.add(employee);
        }
        answer.close();
    } catch (NamingException ex) {
        throw new RuntimeException("Error getting Employees ", ex);
    } catch (IllegalAccessException ex) {
        throw new RuntimeException("Cannot create Employee object ", ex);
    } catch (InvocationTargetException ex) {
        throw new RuntimeException("Cannot create Employee object ", ex);
    } finally {
        closeContext(ctx);
    }
    return employees;
}
Also used : Employee(com.artezio.arttime.datamodel.Employee) ArrayList(java.util.ArrayList) InitialLdapContext(javax.naming.ldap.InitialLdapContext) Attributes(javax.naming.directory.Attributes) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 38 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project ART-TIME by Artezio.

the class LdapAdapter method initializeContext.

protected InitialLdapContext initializeContext(String principal, String credentials) throws NamingException {
    Properties env = new Properties();
    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    String providerUrl = String.format("ldap://%s:%d", getServerAddress(), getServerPort());
    env.setProperty(Context.PROVIDER_URL, providerUrl);
    env.setProperty(Context.SECURITY_PRINCIPAL, principal);
    env.setProperty(Context.SECURITY_CREDENTIALS, credentials);
    InitialLdapContext ctx = new InitialLdapContext(env, null);
    return ctx;
}
Also used : InitialLdapContext(javax.naming.ldap.InitialLdapContext) Properties(java.util.Properties)

Example 39 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project wildfly by wildfly.

the class OtpSaslTestCase method assertSequenceAndHash.

/**
 * Check correct user attribute values in the LDAP when using OTP algorithm.
 */
private void assertSequenceAndHash(Integer expectedSequence, byte[] expectedHash) throws NamingException {
    final Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, LDAP_URL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    final LdapContext ctx = new InitialLdapContext(env, null);
    NamingEnumeration<?> namingEnum = ctx.search("dc=wildfly,dc=org", new BasicAttributes("cn", "jduke"));
    if (namingEnum.hasMore()) {
        SearchResult sr = (SearchResult) namingEnum.next();
        Attributes attrs = sr.getAttributes();
        assertEquals("Unexpected sequence number in LDAP attribute", expectedSequence, new Integer(attrs.get("telephoneNumber").get().toString()));
        assertEquals("Unexpected hash value in LDAP attribute", Base64.getEncoder().encodeToString(expectedHash), attrs.get("title").get().toString());
    } else {
        fail("User not found in LDAP");
    }
    namingEnum.close();
    ctx.close();
}
Also used : BasicAttributes(javax.naming.directory.BasicAttributes) InitialLdapContext(javax.naming.ldap.InitialLdapContext) BasicAttributes(javax.naming.directory.BasicAttributes) Attributes(javax.naming.directory.Attributes) SearchResult(javax.naming.directory.SearchResult) Properties(java.util.Properties) InitialLdapContext(javax.naming.ldap.InitialLdapContext) LdapContext(javax.naming.ldap.LdapContext)

Example 40 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project snow-owl by b2ihealthcare.

the class LdapIdentityProvider method searchUsers.

@Override
public Promise<Users> searchUsers(Collection<String> usernames, int limit) {
    final ImmutableList.Builder<User> resultBuilder = ImmutableList.builder();
    final String uidProp = conf.getUserIdProperty();
    InitialLdapContext context = null;
    NamingEnumeration<SearchResult> searchResultEnumeration = null;
    try {
        context = createLdapContext();
        Collection<LdapRole> ldapRoles = getAllLdapRoles(context);
        searchResultEnumeration = context.search(conf.getBaseDn(), conf.getUserFilter(), createSearchControls(ATTRIBUTE_DN, uidProp));
        for (final SearchResult searchResult : ImmutableList.copyOf(Iterators.forEnumeration(searchResultEnumeration))) {
            final Attributes attributes = searchResult.getAttributes();
            if (hasAttribute(attributes, uidProp)) {
                final String userName = (String) attributes.get(uidProp).get();
                final List<Role> userRoles = ldapRoles.stream().filter(role -> role.getUniqueMembers().contains(searchResult.getNameInNamespace())).map(role -> new Role(role.getName(), role.getPermissions())).collect(Collectors.toList());
                resultBuilder.add(new User(userName, userRoles));
            }
        }
        final List<User> users = resultBuilder.build().stream().sorted((u1, u2) -> u1.getUsername().compareTo(u2.getUsername())).filter(user -> usernames.isEmpty() || usernames.contains(user.getUsername())).limit(limit).collect(Collectors.toList());
        return Promise.immediate(new Users(users, limit, users.size()));
    } catch (final NamingException e) {
        LOG.error("Couldn't search users/roles due to LDAP communication error: {}", e.getMessage(), e);
        throw new SnowowlRuntimeException(e);
    } finally {
        closeNamingEnumeration(searchResultEnumeration);
        closeLdapContext(context);
    }
}
Also used : Iterables(com.google.common.collect.Iterables) InitialLdapContext(javax.naming.ldap.InitialLdapContext) Promise(com.b2international.snowowl.core.events.util.Promise) LoggerFactory(org.slf4j.LoggerFactory) NamingException(javax.naming.NamingException) SearchControls(javax.naming.directory.SearchControls) Iterators(com.google.common.collect.Iterators) Attribute(javax.naming.directory.Attribute) Strings(com.google.common.base.Strings) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) Permission(com.b2international.snowowl.core.identity.Permission) Context(javax.naming.Context) NoSuchElementException(java.util.NoSuchElementException) Hashtable(java.util.Hashtable) IdentityProvider(com.b2international.snowowl.core.identity.IdentityProvider) Logger(org.slf4j.Logger) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) Collection(java.util.Collection) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) DirContext(javax.naming.directory.DirContext) Role(com.b2international.snowowl.core.identity.Role) Collectors(java.util.stream.Collectors) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) TreeMap(java.util.TreeMap) Attributes(javax.naming.directory.Attributes) Users(com.b2international.snowowl.core.identity.Users) NamingEnumeration(javax.naming.NamingEnumeration) User(com.b2international.snowowl.core.identity.User) Preconditions(com.google.common.base.Preconditions) Collections(java.util.Collections) SearchResult(javax.naming.directory.SearchResult) User(com.b2international.snowowl.core.identity.User) ImmutableList(com.google.common.collect.ImmutableList) Attributes(javax.naming.directory.Attributes) SearchResult(javax.naming.directory.SearchResult) Users(com.b2international.snowowl.core.identity.Users) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException) Role(com.b2international.snowowl.core.identity.Role) InitialLdapContext(javax.naming.ldap.InitialLdapContext) NamingException(javax.naming.NamingException)

Aggregations

InitialLdapContext (javax.naming.ldap.InitialLdapContext)54 NamingException (javax.naming.NamingException)30 Hashtable (java.util.Hashtable)17 LdapContext (javax.naming.ldap.LdapContext)17 Attributes (javax.naming.directory.Attributes)16 Properties (java.util.Properties)14 SearchResult (javax.naming.directory.SearchResult)14 IOException (java.io.IOException)11 AuthenticationException (javax.naming.AuthenticationException)10 NamingEnumeration (javax.naming.NamingEnumeration)10 StartTlsRequest (javax.naming.ldap.StartTlsRequest)10 BasicAttributes (javax.naming.directory.BasicAttributes)9 Attribute (javax.naming.directory.Attribute)8 SearchControls (javax.naming.directory.SearchControls)8 LdapConfigProperties (org.bedework.calfacade.configs.LdapConfigProperties)7 CalFacadeException (org.bedework.calfacade.exc.CalFacadeException)7 StartTlsResponse (javax.naming.ldap.StartTlsResponse)6 CommunicationException (javax.naming.CommunicationException)5 DirContext (javax.naming.directory.DirContext)5 BwGroup (org.bedework.calfacade.BwGroup)5