Package org.apache.directory.ldap.client.api

Examples of org.apache.directory.ldap.client.api.LdapNetworkConnection


        }
        config.setName(ldapSettings.getSystemUserName());
        config.setCredentials(ldapSettings.getSystemPassword());

        final String principal = String.valueOf(token.getPrincipal());
        LdapNetworkConnection connection = null;
        try {
            connection = ldapConnector.connect(config);

            if(null == connection) {
                LOG.error("Couldn't connect to LDAP directory");
                return null;
            }

            final String password = String.valueOf(token.getPassword());

            final LdapEntry userEntry = ldapConnector.search(connection,
                                                             ldapSettings.getSearchBase(),
                                                             ldapSettings.getSearchPattern(),
                                                             principal,
                                                             ldapSettings.isActiveDirectory());
            if (userEntry == null) {
                LOG.debug("User {} not found in LDAP", principal);
                return null;
            }

            // needs to use the DN of the entry, not the parameter for the lookup filter we used to find the entry!
            final boolean authenticated = ldapConnector.authenticate(connection,
                                                                     userEntry.getDn(),
                                                                     password);
            if (!authenticated) {
                LOG.info("Invalid credentials for user {} (DN {})", principal, userEntry.getDn());
                return null;
            }
            // user found and authenticated, sync the user entry with mongodb
            final User user = userService.syncFromLdapEntry(userEntry, ldapSettings, principal);
            if (user == null) {
                // in case there was an error reading, creating or modifying the user in mongodb, we do not authenticate the user.
                LOG.error("Unable to sync LDAP user {}", userEntry.getDn());
                return null;
            }
        } catch (LdapException e) {
            LOG.error("LDAP error", e);
            return null;
        } catch (CursorException e) {
            LOG.error("Unable to read LDAP entry", e);
            return null;
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (IOException e) {
                    LOG.error("Unable to close LDAP connection", e);
                }
            }
        }
View Full Code Here


    public LdapConnector(final int connectionTimeout) {
        this.connectionTimeout = connectionTimeout;
    }

    public LdapNetworkConnection connect(LdapConnectionConfig config) throws LdapException {
        final LdapNetworkConnection connection = new LdapNetworkConnection(config);
        connection.setTimeOut(connectionTimeout);

        if (LOG.isTraceEnabled()) {
            LOG.trace("Connecting to LDAP server {}:{}, binding with user {}",
                      config.getLdapHost(), config.getLdapPort(), config.getName());
        }

        // this will perform an anonymous bind if there were no system credentials
        final SimpleTimeLimiter timeLimiter = new SimpleTimeLimiter(Executors.newSingleThreadExecutor());
        @SuppressWarnings("unchecked")
        final Callable<Boolean> timeLimitedConnection = timeLimiter.newProxy(
                new Callable<Boolean>() {
                    @Override
                    public Boolean call() throws Exception {
                        return connection.connect();
                    }
                }, Callable.class,
                connectionTimeout, TimeUnit.MILLISECONDS);
        try {
            final Boolean connected = timeLimitedConnection.call();
            if (!connected) {
                return null;
            }
        } catch (UncheckedTimeoutException e) {
            LOG.error("Timed out connecting to LDAP server", e);
            throw new LdapException("Could not connect to LDAP server", e.getCause());
        } catch (LdapException e) {
            throw e;
        } catch (Exception e) {
            // unhandled different exception, should really not happen here.
            throw new LdapException("Unexpected error connecting to LDAP", e);
        }
        connection.bind();

        return connection;
    }
View Full Code Here

        if (request.systemUsername != null && !request.systemUsername.isEmpty()) {
            config.setName(request.systemUsername);
            config.setCredentials(request.systemPassword);
        }

        LdapNetworkConnection connection = null;
        try {
            try {
                connection = ldapConnector.connect(config);
            } catch (LdapException e) {
                response.exception = e.getMessage();
                response.connected = false;
                response.systemAuthenticated = false;
                return response;
            }

            if (null == connection) {
                response.connected = false;
                response.systemAuthenticated = false;
                response.exception = "Could not connect to LDAP server";
                return response;
            }

            response.connected = connection.isConnected();
            response.systemAuthenticated = connection.isAuthenticated();

            // the web interface allows testing the connection only, in that case we can bail out early.
            if (request.testConnectOnly) {
                return response;
            }

            String userPrincipalName = null;
            try {
                final LdapEntry entry = ldapConnector.search(
                        connection,
                        request.searchBase,
                        request.searchPattern,
                        request.principal,
                        request.activeDirectory);
                if (entry != null) {
                    userPrincipalName = entry.getDn();
                    response.entry = entry.getAttributes();
                }
            } catch (CursorException | LdapException e) {
                response.entry = null;
                response.exception = e.getMessage();
            }

            try {
                response.loginAuthenticated = ldapConnector.authenticate(connection, userPrincipalName, request.password);
            } catch (Exception e) {
                response.loginAuthenticated = false;
                response.exception = e.getMessage();
            }

            return response;
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (IOException e) {
                    LOG.warn("Unable to close LDAP connection.", e);
                }
            }
        }
View Full Code Here

    @Test
    public void testAddPDUExceedingMaxSizeLdapApi() throws Exception
    {
        // Limit the PDU size to 1024
        getLdapServer().getDirectoryService().setMaxPDUSize( 1024 );
        LdapConnection connection = new LdapNetworkConnection( "localhost", getLdapServer().getPort() );
        connection.bind( "uid=admin,ou=system", "secret" );

        // Inject a 1024 bytes long description
        StringBuilder sb = new StringBuilder();

        for ( int i = 0; i < 128; i++ )
        {
            sb.append( "0123456789ABCDEF" );
        }

        Attribute description = new DefaultAttribute( "description", sb.toString() );

        try
        {
            Modification modification = new DefaultModification( ModificationOperation.ADD_ATTRIBUTE, description );
            connection.modify( "cn=the person, ou=system", modification );
            fail();
        }
        catch ( Exception e )
        {
            // We are expecting the session to be close here.
            if ( connection.isConnected() )
            {
                // Race condition:
                // Upon NoticeOfDisconnection the API sends an abandon request but does not immediately close the connection.
                // So at this point it is not guaranteed that the connnection is already closed.
                // TODO: This is just a workaround, better check the connection for any outstanding abandon requests
                Thread.sleep( 1000 );
            }
            assertFalse( connection.isConnected() );
        }
    }
View Full Code Here

     * Create the LdapConnection
     */
    @Before
    public void setup() throws Exception
    {
        connection = new LdapNetworkConnection( "localhost", getLdapServer().getPort() );
        connection.setTimeOut( 0L );
    }
View Full Code Here

    public void testSimpleBindAnonymous() throws Exception
    {
        getLdapServer().getDirectoryService().setAllowAnonymousAccess( true );

        //System.out.println( "------------------Create connection" + i + "-------------" );
        LdapConnection connection = new LdapNetworkConnection( "localhost", getLdapServer().getPort() );
        //System.out.println( "------------------Bind" + i + "-------------" );

        // Try with no parameters
        connection.anonymousBind();

        assertTrue( connection.isAuthenticated() );

        //System.out.println( "----------------Unbind" + i + "-------------" );
        connection.unBind();
        assertFalse( connection.isConnected() );
        connection.close();

        // Try with empty strings
        connection = new LdapNetworkConnection( "localhost", getLdapServer().getPort() );
        connection.bind( "", "" );

        assertTrue( connection.isAuthenticated() );

        connection.unBind();
        assertFalse( connection.isConnected() );
        connection.close();

        // Try with null parameters
        connection = new LdapNetworkConnection( "localhost", getLdapServer().getPort() );
        connection.bind( ( String ) null, ( String ) null );

        assertTrue( connection.isAuthenticated() );
        assertTrue( connection.isConnected() );

        connection.unBind();
        assertFalse( connection.isConnected() );
        connection.close();

        connection = new LdapNetworkConnection( "localhost", getLdapServer().getPort() );

        //System.out.println( "----------------Unbind done" + i + "-------------" );
        assertFalse( connection.isConnected() );
        connection.close();
        //System.out.println( "----------------Unconnected" + i + "-------------" );
    }
View Full Code Here

        LdapConnectionConfig config = new LdapConnectionConfig();
        config.setLdapHost( "localhost" );
        config.setLdapPort( getLdapServer().getPort() );
        config.setName( "uid=nonexisting,dc=example,dc=com" );

        connection = new LdapNetworkConnection( config );
        connection.anonymousBind();

        assertTrue( connection.isAuthenticated() );
    }
View Full Code Here

     * Test for DIRSERVER-1908
     */
    @Test
    public void testPsearchMove() throws Exception
    {
        LdapNetworkConnection connection = new LdapNetworkConnection( "localhost", ldapServer.getPort() );
        connection.bind( "uid=admin,ou=system", "secret" );
       
        Entry newOu = new DefaultEntry( "uid=persist, ou=users,ou=system" );
        newOu.add( "objectClass", "inetOrgPerson" );
        newOu.add( "cn", "persist_cn" );
        newOu.add( "sn", "persist_sn" );
       
        connection.add( newOu );
       
        SearchRequest sr = new SearchRequestImpl();
        sr.setBase( new Dn( BASE ) );
        sr.setFilter( "(objectClass=*)" );
        sr.setScope( SearchScope.SUBTREE );
       
        PersistentSearch ps = new PersistentSearchImpl();
        ps.setChangesOnly( true );
        ps.setReturnECs( true );
        ps.setCritical( true );
       
        sr.addControl( ps );
       
        final SearchCursor cursor = connection.search( sr );
       
        final List<Entry> entryList = new ArrayList<Entry>();
       
        Runnable r = new Runnable()
        {
           
            @Override
            public void run()
            {
                try
                {
                    while( cursor.next() )
                    {
                        entryList.add( cursor.getEntry() );
                    }
                }
                catch( Exception e )
                {
                    throw new RuntimeException( e );
                }
            }
        };
       
        new Thread( r ).start();
       
        connection.move( newOu.getDn(), newOu.getDn().getParent().getParent() );
        Thread.sleep( 1000 );
        assertFalse( entryList.isEmpty() );
        assertEquals( 1, entryList.size() );
        assertEquals( "uid=persist,ou=system", entryList.get( 0 ).getDn().getName() );
       
        connection.close();
    }
View Full Code Here

            if( url.getScheme().equals( "ldaps" ) )
            {
                useSsl = true;
            }
           
            LdapNetworkConnection c = new LdapNetworkConnection( url.getHost(), url.getPort(), useSsl );
            c.setTimeOut( Long.MAX_VALUE );
            c.connect();
            c.bind( ServerDNConstants.ADMIN_SYSTEM_DN, "secret" );
            System.out.println( "connected to the server " + url );
            connections.add( c );
        }
    }
View Full Code Here

       
        for( int i=0; i < batch; i++ )
        {
            int index = rand.nextInt( connections.size() );

            LdapNetworkConnection nc = connections.get( index );
           
            if( verbose )
            {
                System.out.println( "inserting into the server " + nc.getConfig().getLdapHost() + ":" + nc.getConfig().getLdapPort() );
            }
           
            Entry e = createEntry( count.incrementAndGet() );
            if ( inject( nc, e ) )
            {
View Full Code Here

TOP

Related Classes of org.apache.directory.ldap.client.api.LdapNetworkConnection

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.