Search in sources :

Example 41 with InitialLdapContext

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

the class LdapIdentityProvider method validateSettings.

@Override
public void validateSettings() throws Exception {
    InitialLdapContext systemContext = null;
    try {
        systemContext = createLdapContext();
        getAllLdapRoles(systemContext);
    } catch (final NamingException e) {
        throw new SnowowlRuntimeException("Check LDAP identity provider settings, one or more parameters are invalid.", e);
    } finally {
        closeLdapContext(systemContext);
    }
}
Also used : InitialLdapContext(javax.naming.ldap.InitialLdapContext) NamingException(javax.naming.NamingException) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException)

Example 42 with InitialLdapContext

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

the class LdapIdentityProvider method auth.

@Override
public User auth(String username, String token) {
    InitialLdapContext systemContext = null;
    try {
        systemContext = createLdapContext();
        final String userDN = findUserDN(systemContext, username);
        if (!Strings.isNullOrEmpty(userDN) && authenticateUser(userDN, token)) {
            return searchUsers(Collections.singleton(username), 1).getSync(1, TimeUnit.MINUTES).first().get();
        } else {
            return null;
        }
    } catch (final NamingException e) {
        throw new SnowowlRuntimeException("Cannot bind to LDAP server.", e);
    } finally {
        closeLdapContext(systemContext);
    }
}
Also used : InitialLdapContext(javax.naming.ldap.InitialLdapContext) NamingException(javax.naming.NamingException) SnowowlRuntimeException(com.b2international.snowowl.core.api.SnowowlRuntimeException)

Example 43 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project ranger by apache.

the class LdapConfigCheckMain method main.

public static void main(String[] args) {
    CommandLineOptions cli = new CommandLineOptions(args);
    cli.parse();
    String inFileName = cli.getInput();
    String outputDir = cli.getOutput();
    if (!outputDir.endsWith("/")) {
        outputDir = outputDir.concat("/");
    }
    LdapConfig config = new LdapConfig(inFileName, cli.getBindPassword());
    if (cli.getLdapUrl() != null && !cli.getLdapUrl().isEmpty()) {
        config.updateInputPropFile(cli.getLdapUrl(), cli.getBindDn(), cli.getBindPassword(), cli.getUserSearchBase(), cli.getUserSearchFilter(), cli.getAuthUser(), cli.getAuthPass());
    }
    PrintStream logFile = null;
    PrintStream ambariProps = null;
    PrintStream installProps = null;
    LdapContext ldapContext = null;
    try {
        logFile = new PrintStream(new File(outputDir + LOG_FILE));
        ambariProps = new PrintStream(new File(outputDir + AMBARI_PROPERTIES));
        installProps = new PrintStream(new File(outputDir + INSTALL_PROPERTIES));
        UserSync userSyncObj = new UserSync(config, logFile, ambariProps, installProps);
        String bindDn = config.getLdapBindDn();
        Properties env = new Properties();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, config.getLdapUrl());
        env.put(Context.SECURITY_PRINCIPAL, bindDn);
        env.put(Context.SECURITY_CREDENTIALS, cli.getBindPassword());
        env.put(Context.SECURITY_AUTHENTICATION, config.getLdapAuthenticationMechanism());
        env.put(Context.REFERRAL, "follow");
        ldapContext = new InitialLdapContext(env, null);
        if (config.isPagedResultsEnabled()) {
            ldapContext.setRequestControls(new Control[] { new PagedResultsControl(config.getPagedResultsSize(), Control.CRITICAL) });
        }
        String retrieveValues = "all";
        if (cli.getDiscoverProperties() != null) {
            retrieveValues = cli.getDiscoverProperties();
            if (cli.getDiscoverProperties().equalsIgnoreCase("users")) {
                userSyncObj.findUserProperties(ldapContext);
            } else if (cli.getDiscoverProperties().equalsIgnoreCase("groups")) {
                userSyncObj.findGroupProperties(ldapContext);
            } else {
                findAllUserSyncProperties(ldapContext, userSyncObj);
            }
        } else if (cli.getRetrieveValues() != null) {
            retrieveValues = cli.getRetrieveValues();
        } else {
            cli.help();
        }
        if (cli.isAuthEnabled()) {
            authenticate(userSyncObj, config, logFile, ambariProps, installProps);
        }
        retrieveUsersGroups(ldapContext, userSyncObj, retrieveValues);
        if (ldapContext != null) {
            ldapContext.close();
        }
    } catch (FileNotFoundException fe) {
        System.out.println(fe.getMessage());
    } catch (IOException ioe) {
        logFile.println("ERROR: Failed while setting the paged results controls\n" + ioe);
    } catch (NamingException ne) {
        System.out.println("ERROR: Failed to perfom ldap bind. Please verify values for " + "ranger.usersync.ldap.binddn and ranger.usersync.ldap.ldapbindpassword\n" + ne);
    } catch (Throwable t) {
        if (logFile != null) {
            logFile.println("ERROR: Connection failed: " + t.getMessage());
        } else {
            System.out.println("ERROR: Connection failed: " + t.getMessage());
        }
    } finally {
        if (logFile != null) {
            logFile.close();
        }
        if (ambariProps != null) {
            ambariProps.close();
        }
        if (installProps != null) {
            installProps.close();
        }
        try {
            if (ldapContext != null) {
                ldapContext.close();
            }
        } catch (NamingException ne) {
            System.out.println("Failed to close LdapContext!");
        }
    }
}
Also used : PrintStream(java.io.PrintStream) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) Properties(java.util.Properties) InitialLdapContext(javax.naming.ldap.InitialLdapContext) NamingException(javax.naming.NamingException) File(java.io.File) InitialLdapContext(javax.naming.ldap.InitialLdapContext) LdapContext(javax.naming.ldap.LdapContext) PagedResultsControl(javax.naming.ldap.PagedResultsControl)

Example 44 with InitialLdapContext

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

the class LdapClientTest method testListUsers.

@Test
public void testListUsers() throws Exception {
    final String userContextDN = "user-cdn";
    final String filterExpression = "filter-expr";
    final Object[] filterArgs = new Object[] {};
    LdapClient.Filter mockFilter = createMock(LdapClient.Filter.class);
    expect(mockFilter.getExpression()).andReturn(filterExpression).anyTimes();
    expect(mockFilter.getArgs()).andReturn(filterArgs).anyTimes();
    SearchControls mockControls = createMock(SearchControls.class);
    InitialLdapContext mockContext = createMock(InitialLdapContext.class);
    ldapClient = createMockBuilder(LdapClient.class).addMockedMethod("initializeContext", new Class[] {}).addMockedMethod("makeSearchControls").createMock();
    settings.setLdapUserContextDN(userContextDN);
    setField(ldapClient, "settings", settings);
    setAttributeMapping();
    NamingEnumeration enumeration = createMock(NamingEnumeration.class);
    SearchResult result1 = createMock(SearchResult.class);
    SearchResult result2 = createMock(SearchResult.class);
    expect(enumeration.hasMore()).andReturn(true).times(2);
    expect(enumeration.hasMore()).andReturn(false).once();
    expect(enumeration.next()).andReturn(result1).once();
    expect(enumeration.next()).andReturn(result2).once();
    enumeration.close();
    expectLastCall().andVoid();
    Employee expectedEmployee1 = new Employee("uname1", "fname1", "lname1", "email1", "dep1");
    Employee expectedEmployee2 = new Employee("uname2", "fname2", "lname2", "email2", "dep2");
    expect(result1.getAttributes()).andReturn(getAttributesFor(expectedEmployee1));
    expect(result2.getAttributes()).andReturn(getAttributesFor(expectedEmployee2));
    expect(ldapClient.makeSearchControls()).andReturn(mockControls);
    expect(ldapClient.initializeContext()).andReturn(mockContext);
    mockContext.close();
    expectLastCall().once().andVoid();
    expect(mockContext.search(eq(userContextDN), eq(filterExpression), eq(filterArgs), eq(mockControls))).andReturn(enumeration);
    replay(ldapClient, mockContext, mockControls, mockFilter, enumeration, result1, result2);
    List<UserInfo> actualList = ldapClient.listUsers(mockFilter);
    assertEquals(2, actualList.size());
    UserInfo actualUser1 = actualList.stream().filter(e -> e.getUsername().equals(expectedEmployee1.getUserName())).findFirst().get();
    UserInfo actualUser2 = actualList.stream().filter(e -> e.getUsername().equals(expectedEmployee2.getUserName())).findFirst().get();
    assertTrue(isEmployeeFullyEqualToUserInfo(expectedEmployee1, actualUser1));
    assertTrue(isEmployeeFullyEqualToUserInfo(expectedEmployee2, actualUser2));
}
Also used : NamingEnumeration(javax.naming.NamingEnumeration) SearchResult(javax.naming.directory.SearchResult) UserInfo(com.artezio.arttime.services.integration.spi.UserInfo) Employee(com.artezio.arttime.datamodel.Employee) InitialLdapContext(javax.naming.ldap.InitialLdapContext) SearchControls(javax.naming.directory.SearchControls) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 45 with InitialLdapContext

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

the class LdapClient method listUsers.

protected List<UserInfo> listUsers(Filter filter) {
    List<UserInfo> users = new ArrayList<>();
    InitialLdapContext ctx = null;
    try {
        ctx = initializeContext();
        SearchControls controls = makeSearchControls();
        NamingEnumeration<SearchResult> answer = ctx.search(settings.getLdapUserContextDN(), filter.getExpression(), filter.getArgs(), controls);
        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            Attributes attrs = sr.getAttributes();
            UserInfo user = createUserInfo(attrs);
            users.add(user);
        }
        answer.close();
    } catch (NamingException ex) {
        throw new RuntimeException("Error listing users ", ex);
    } finally {
        closeContext(ctx);
    }
    return users;
}
Also used : InitialLdapContext(javax.naming.ldap.InitialLdapContext) Attributes(javax.naming.directory.Attributes) UserInfo(com.artezio.arttime.services.integration.spi.UserInfo) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) 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