Package com.unboundid.ldap.sdk

Examples of com.unboundid.ldap.sdk.LDAPConnection


  public synchronized void sync() {
    final boolean enabled = settings.getBoolean(Keys.realm.ldap.synchronize, false);
    if (enabled) {
      logger.info("Synchronizing with LDAP @ " + settings.getRequiredString(Keys.realm.ldap.server));
      final boolean deleteRemovedLdapUsers = settings.getBoolean(Keys.realm.ldap.removeDeletedUsers, true);
      LDAPConnection ldapConnection = getLdapConnection();
      if (ldapConnection != null) {
        try {
          String accountBase = settings.getString(Keys.realm.ldap.accountBase, "");
          String uidAttribute = settings.getString(Keys.realm.ldap.uid, "uid");
          String accountPattern = settings.getString(Keys.realm.ldap.accountPattern, "(&(objectClass=person)(sAMAccountName=${username}))");
          accountPattern = StringUtils.replace(accountPattern, "${username}", "*");

          SearchResult result = doSearch(ldapConnection, accountBase, accountPattern);
          if (result != null && result.getEntryCount() > 0) {
            final Map<String, UserModel> ldapUsers = new HashMap<String, UserModel>();

            for (SearchResultEntry loggingInUser : result.getSearchEntries()) {
              Attribute uid = loggingInUser.getAttribute(uidAttribute);
              if (uid == null) {
                logger.error("Can not synchronize with LDAP, missing \"{}\" attribute", uidAttribute);
                continue;
              }
              final String username = uid.getValue();
              logger.debug("LDAP synchronizing: " + username);

              UserModel user = userManager.getUserModel(username);
              if (user == null) {
                user = new UserModel(username);
              }

              if (!supportsTeamMembershipChanges()) {
                getTeamsFromLdap(ldapConnection, username, loggingInUser, user);
              }

              // Get User Attributes
              setUserAttributes(user, loggingInUser);

              // store in map
              ldapUsers.put(username.toLowerCase(), user);
            }

            if (deleteRemovedLdapUsers) {
              logger.debug("detecting removed LDAP users...");

              for (UserModel userModel : userManager.getAllUsers()) {
                if (AccountType.LDAP == userModel.accountType) {
                  if (!ldapUsers.containsKey(userModel.username)) {
                    logger.info("deleting removed LDAP user " + userModel.username + " from user service");
                    userManager.deleteUser(userModel.username);
                  }
                }
              }
            }

            userManager.updateUserModels(ldapUsers.values());

            if (!supportsTeamMembershipChanges()) {
              final Map<String, TeamModel> userTeams = new HashMap<String, TeamModel>();
              for (UserModel user : ldapUsers.values()) {
                for (TeamModel userTeam : user.teams) {
                  userTeams.put(userTeam.name, userTeam);
                }
              }
              userManager.updateTeamModels(userTeams.values());
            }
          }
          if (!supportsTeamMembershipChanges()) {
            getEmptyTeamsFromLdap(ldapConnection);
          }
        } finally {
          ldapConnection.close();
        }
      }
    }
  }
View Full Code Here


      String ldapHost = ldapUrl.getHost();
      int ldapPort = ldapUrl.getPort();
      String bindUserName = settings.getString(Keys.realm.ldap.username, "");
      String bindPassword = settings.getString(Keys.realm.ldap.password, "");

      LDAPConnection conn;
      if (ldapUrl.getScheme().equalsIgnoreCase("ldaps")) {
        // SSL
        SSLUtil sslUtil = new SSLUtil(new TrustAllTrustManager());
        conn = new LDAPConnection(sslUtil.createSSLSocketFactory());
        if (ldapPort == -1) {
          ldapPort = 636;
        }
      } else if (ldapUrl.getScheme().equalsIgnoreCase("ldap") || ldapUrl.getScheme().equalsIgnoreCase("ldap+tls")) {
        // no encryption or StartTLS
        conn = new LDAPConnection();
         if (ldapPort == -1) {
           ldapPort = 389;
         }
      } else {
        logger.error("Unsupported LDAP URL scheme: " + ldapUrl.getScheme());
        return null;
      }

      conn.connect(ldapHost, ldapPort);

      if (ldapUrl.getScheme().equalsIgnoreCase("ldap+tls")) {
        SSLUtil sslUtil = new SSLUtil(new TrustAllTrustManager());
        ExtendedResult extendedResult = conn.processExtendedOperation(
            new StartTLSExtendedRequest(sslUtil.createSSLContext()));
        if (extendedResult.getResultCode() != ResultCode.SUCCESS) {
          throw new LDAPException(extendedResult.getResultCode());
        }
      }

      if (StringUtils.isEmpty(bindUserName) && StringUtils.isEmpty(bindPassword)) {
        // anonymous bind
        conn.bind(new SimpleBindRequest());
      } else {
        // authenticated bind
        conn.bind(new SimpleBindRequest(bindUserName, bindPassword));
      }

      return conn;

    } catch (URISyntaxException e) {
View Full Code Here

  @Override
  public UserModel authenticate(String username, char[] password) {
    String simpleUsername = getSimpleUsername(username);

    LDAPConnection ldapConnection = getLdapConnection();
    if (ldapConnection != null) {
      try {
        boolean alreadyAuthenticated = false;

        String bindPattern = settings.getString(Keys.realm.ldap.bindpattern, "");
        if (!StringUtils.isEmpty(bindPattern)) {
          try {
            String bindUser = StringUtils.replace(bindPattern, "${username}", escapeLDAPSearchFilter(simpleUsername));
            ldapConnection.bind(bindUser, new String(password));

            alreadyAuthenticated = true;
          } catch (LDAPException e) {
            return null;
          }
        }

        // Find the logging in user's DN
        String accountBase = settings.getString(Keys.realm.ldap.accountBase, "");
        String accountPattern = settings.getString(Keys.realm.ldap.accountPattern, "(&(objectClass=person)(sAMAccountName=${username}))");
        accountPattern = StringUtils.replace(accountPattern, "${username}", escapeLDAPSearchFilter(simpleUsername));

        SearchResult result = doSearch(ldapConnection, accountBase, accountPattern);
        if (result != null && result.getEntryCount() == 1) {
          SearchResultEntry loggingInUser = result.getSearchEntries().get(0);
          String loggingInUserDN = loggingInUser.getDN();

          if (alreadyAuthenticated || isAuthenticated(ldapConnection, loggingInUserDN, new String(password))) {
            logger.debug("LDAP authenticated: " + username);

            UserModel user = null;
            synchronized (this) {
              user = userManager.getUserModel(simpleUsername);
              if (user == null) {
                // create user object for new authenticated user
                user = new UserModel(simpleUsername);
              }

              // create a user cookie
              setCookie(user, password);

              if (!supportsTeamMembershipChanges()) {
                getTeamsFromLdap(ldapConnection, simpleUsername, loggingInUser, user);
              }

              // Get User Attributes
              setUserAttributes(user, loggingInUser);

              // Push the ldap looked up values to backing file
              updateUser(user);

              if (!supportsTeamMembershipChanges()) {
                for (TeamModel userTeam : user.teams) {
                  updateTeam(userTeam);
                }
              }
            }

            return user;
          }
        }
      } finally {
        ldapConnection.close();
      }
    }
    return null;
  }
View Full Code Here

  public synchronized void sync() {
    final boolean enabled = settings.getBoolean(Keys.realm.ldap.synchronize, false);
    if (enabled) {
      logger.info("Synchronizing with LDAP @ " + settings.getRequiredString(Keys.realm.ldap.server));
      final boolean deleteRemovedLdapUsers = settings.getBoolean(Keys.realm.ldap.removeDeletedUsers, true);
      LDAPConnection ldapConnection = getLdapConnection();
      if (ldapConnection != null) {
        try {
          String accountBase = settings.getString(Keys.realm.ldap.accountBase, "");
          String uidAttribute = settings.getString(Keys.realm.ldap.uid, "uid");
          String accountPattern = settings.getString(Keys.realm.ldap.accountPattern, "(&(objectClass=person)(sAMAccountName=${username}))");
          accountPattern = StringUtils.replace(accountPattern, "${username}", "*");

          SearchResult result = doSearch(ldapConnection, accountBase, accountPattern);
          if (result != null && result.getEntryCount() > 0) {
            final Map<String, UserModel> ldapUsers = new HashMap<String, UserModel>();

            for (SearchResultEntry loggingInUser : result.getSearchEntries()) {
              Attribute uid = loggingInUser.getAttribute(uidAttribute);
              if (uid == null) {
                logger.error("Can not synchronize with LDAP, missing \"{}\" attribute", uidAttribute);
                continue;
              }
              final String username = uid.getValue();
              logger.debug("LDAP synchronizing: " + username);

              UserModel user = userManager.getUserModel(username);
              if (user == null) {
                user = new UserModel(username);
              }

              if (!supportsTeamMembershipChanges()) {
                getTeamsFromLdap(ldapConnection, username, loggingInUser, user);
              }

              // Get User Attributes
              setUserAttributes(user, loggingInUser);

              // store in map
              ldapUsers.put(username.toLowerCase(), user);
            }

            if (deleteRemovedLdapUsers) {
              logger.debug("detecting removed LDAP users...");

              for (UserModel userModel : userManager.getAllUsers()) {
                if (AccountType.LDAP == userModel.accountType) {
                  if (!ldapUsers.containsKey(userModel.username)) {
                    logger.info("deleting removed LDAP user " + userModel.username + " from user service");
                    userManager.deleteUser(userModel.username);
                  }
                }
              }
            }

            userManager.updateUserModels(ldapUsers.values());

            if (!supportsTeamMembershipChanges()) {
              final Map<String, TeamModel> userTeams = new HashMap<String, TeamModel>();
              for (UserModel user : ldapUsers.values()) {
                for (TeamModel userTeam : user.teams) {
                  userTeams.put(userTeam.name, userTeam);
                }
              }
              userManager.updateTeamModels(userTeams.values());
            }
          }
          if (!supportsTeamMembershipChanges()) {
            getEmptyTeamsFromLdap(ldapConnection);
          }
        } finally {
          ldapConnection.close();
        }
      }
    }
  }
View Full Code Here

      String ldapHost = ldapUrl.getHost();
      int ldapPort = ldapUrl.getPort();
      String bindUserName = settings.getString(Keys.realm.ldap.username, "");
      String bindPassword = settings.getString(Keys.realm.ldap.password, "");

      LDAPConnection conn;
      if (ldapUrl.getScheme().equalsIgnoreCase("ldaps")) {
        // SSL
        SSLUtil sslUtil = new SSLUtil(new TrustAllTrustManager());
        conn = new LDAPConnection(sslUtil.createSSLSocketFactory());
        if (ldapPort == -1) {
          ldapPort = 636;
        }
      } else if (ldapUrl.getScheme().equalsIgnoreCase("ldap") || ldapUrl.getScheme().equalsIgnoreCase("ldap+tls")) {
        // no encryption or StartTLS
        conn = new LDAPConnection();
         if (ldapPort == -1) {
           ldapPort = 389;
         }
      } else {
        logger.error("Unsupported LDAP URL scheme: " + ldapUrl.getScheme());
        return null;
      }

      conn.connect(ldapHost, ldapPort);

      if (ldapUrl.getScheme().equalsIgnoreCase("ldap+tls")) {
        SSLUtil sslUtil = new SSLUtil(new TrustAllTrustManager());
        ExtendedResult extendedResult = conn.processExtendedOperation(
            new StartTLSExtendedRequest(sslUtil.createSSLContext()));
        if (extendedResult.getResultCode() != ResultCode.SUCCESS) {
          throw new LDAPException(extendedResult.getResultCode());
        }
      }

      if (StringUtils.isEmpty(bindUserName) && StringUtils.isEmpty(bindPassword)) {
        // anonymous bind
        conn.bind(new SimpleBindRequest());
      } else {
        // authenticated bind
        conn.bind(new SimpleBindRequest(bindUserName, bindPassword));
      }

      return conn;

    } catch (URISyntaxException e) {
View Full Code Here

  @Override
  public UserModel authenticate(String username, char[] password) {
    String simpleUsername = getSimpleUsername(username);

    LDAPConnection ldapConnection = getLdapConnection();
    if (ldapConnection != null) {
      try {
        boolean alreadyAuthenticated = false;

        String bindPattern = settings.getString(Keys.realm.ldap.bindpattern, "");
        if (!StringUtils.isEmpty(bindPattern)) {
          try {
            String bindUser = StringUtils.replace(bindPattern, "${username}", escapeLDAPSearchFilter(simpleUsername));
            ldapConnection.bind(bindUser, new String(password));

            alreadyAuthenticated = true;
          } catch (LDAPException e) {
            return null;
          }
        }

        // Find the logging in user's DN
        String accountBase = settings.getString(Keys.realm.ldap.accountBase, "");
        String accountPattern = settings.getString(Keys.realm.ldap.accountPattern, "(&(objectClass=person)(sAMAccountName=${username}))");
        accountPattern = StringUtils.replace(accountPattern, "${username}", escapeLDAPSearchFilter(simpleUsername));

        SearchResult result = doSearch(ldapConnection, accountBase, accountPattern);
        if (result != null && result.getEntryCount() == 1) {
          SearchResultEntry loggingInUser = result.getSearchEntries().get(0);
          String loggingInUserDN = loggingInUser.getDN();

          if (alreadyAuthenticated || isAuthenticated(ldapConnection, loggingInUserDN, new String(password))) {
            logger.debug("LDAP authenticated: " + username);

            UserModel user = null;
            synchronized (this) {
              user = userManager.getUserModel(simpleUsername);
              if (user == null) {
                // create user object for new authenticated user
                user = new UserModel(simpleUsername);
              }

              // create a user cookie
              setCookie(user, password);

              if (!supportsTeamMembershipChanges()) {
                getTeamsFromLdap(ldapConnection, simpleUsername, loggingInUser, user);
              }

              // Get User Attributes
              setUserAttributes(user, loggingInUser);

              // Push the ldap looked up values to backing file
              updateUser(user);

              if (!supportsTeamMembershipChanges()) {
                for (TeamModel userTeam : user.teams) {
                  updateTeam(userTeam);
                }
              }
            }

            return user;
          }
        }
      } finally {
        ldapConnection.close();
      }
    }
    return null;
  }
View Full Code Here

     * @param port     The TCP port number of the directory server.
     * @throws DirectoryTesterException If there was a problem connecting to the LDAP directory server.
     */
    public DirectoryTester(final String hostname, final int port) {
        try {
            connection = new LDAPConnection(hostname, port);
        } catch (final LDAPException e) {
            throw new DirectoryTesterException("Could not connect to LDAP directory server", e);
        }
    }
View Full Code Here

     * each file using the appropriate handler.
     *
     * @throws MojoExecutionException If there was an error executing the plugin goal.
     */
    public void execute() throws MojoExecutionException {
        final LDAPConnection connection = connect();
        try {
            for (final Source source : sources) {
                try {
                    getLog().info("Processing input source: " + source);
                    final FormatHandler handler = getFormatHandler(source);
                    if (handler == null) {
                        getLog().warn("No handler for input source: " + source);
                    } else {
                        final InputStream inputStream = source.open();
                        if (inputStream == null) {
                            if (!this.continueOnError) {
                                throw new MojoExecutionException("Cannot open source for reading: " + source);
                            } else {
                                getLog().warn("Skipping source that could not be opened for reading: " + source);
                            }
                        } else {
                            try {
                                handler.load(connection, source.open(), continueOnError, this);
                            } finally {
                                inputStream.close();
                            }
                        }
                    }
                } catch (final IOException e) {
                    if (!this.continueOnError) {
                        throw new MojoExecutionException("Error closing input source: " + source, e);
                    } else {
                        this.getLog().warn("Ignoring error closing input source: " + source, e);
                    }
                }
            }
        } finally {
            connection.close();
        }
    }
View Full Code Here

        final File outputFile = new File(outputDirectory, filename);
        if (outputDirectory.exists() || outputDirectory.mkdirs()) {
            try {
                final OutputStream outputStream = new FileOutputStream(outputFile);
                try {
                    final LDAPConnection connection = connect();
                    try {
                        final FormatHandler handler = getFormatHandler();
                        handler.dump(connection, searchBase, searchFilter, outputStream, this);
                    } finally {
                        connection.close();
                    }
                } finally {
                    try {
                        outputStream.close();
                    } catch (final IOException e) {
View Full Code Here

     *
     * @return The connection object.
     * @throws MojoExecutionException If the connection to the LDAP directory server failed.
     */
    protected final LDAPConnection connect() throws MojoExecutionException {
        final LDAPConnection connection = new LDAPConnection();
        int i = 0;
        while (i < connectionRetries) {
            long start = System.currentTimeMillis();
            try {
                this.getLog().info("Attempting to connect ot LDAP directory server (" + host + ":" + port + ")");
                connection.connect(host, port, connectionTimeout);
                break;
            } catch (final LDAPException e) {
                final String message = "Could not connect to LDAP directory server (" + host + ":" + port + ")";
                this.getLog().error(message, e);
                if (i++ < connectionRetries) {
                    long time = System.currentTimeMillis() - start;
                    if (time < connectionTimeout) {
                        try {
                            Thread.sleep(connectionTimeout - time);
                        } catch (final InterruptedException e1) {
                            throw new MojoExecutionException(message, e1);
                        }
                    }
                } else {
                    throw new MojoExecutionException(message, e);
                }
            }
        }
        try {
            connection.bind(authDn, passwd);
        } catch (final LDAPException e) {
            throw new MojoExecutionException("Could not bind to LDAP directory server as " + authDn, e);
        }
        return connection;
    }
View Full Code Here

TOP

Related Classes of com.unboundid.ldap.sdk.LDAPConnection

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.