Exemplo n.º 1
0
  @Test
  public void testLdapExample2() throws Exception {
    System.out.println("testLdapExample2");

    SearchControls constraints = new SearchControls();
    constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String[] attrIDs = {"cn"};
    constraints.setReturningAttributes(attrIDs);
    Hashtable<String, Object> options = new Hashtable<String, Object>();
    options.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
    options.put("java.naming.provider.url", "ldap://127.0.0.1:10389/");
    options.put("java.naming.security.authentication", "simple");
    options.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    options.put(Context.SECURITY_CREDENTIALS, "secret");

    LdapContext ctx = new InitialLdapContext(options, null);
    String username = "******";

    NamingEnumeration<SearchResult> answer =
        ctx.search("ou=users,o=jtogaf", "uid=" + username, constraints);
    assertTrue("There is att: ", answer.hasMore());

    if (answer.hasMore()) {
      Attributes attrs = ((SearchResult) answer.next()).getAttributes();
      Attribute attr = (Attribute) attrs.get("cn");
      System.out.print(attr.get(0));
    }
  }
Exemplo n.º 2
0
 private List<TolvenPerson> findTolvenPerson(
     LdapContext ctx,
     String peopleBaseName,
     String principalLdapName,
     String realm,
     int maxResults,
     int timeLimit) {
   NamingEnumeration<SearchResult> namingEnum = null;
   SearchControls ctls = new SearchControls();
   ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
   ctls.setCountLimit(maxResults);
   ctls.setTimeLimit(timeLimit);
   ArrayList<TolvenPerson> searchResults = new ArrayList<TolvenPerson>(10);
   try {
     namingEnum = ctx.search(peopleBaseName, principalLdapName, ctls);
     while (namingEnum.hasMore()) {
       SearchResult rslt = namingEnum.next();
       searchResults.add(new TolvenPerson(rslt));
     }
   } catch (GatekeeperSecurityException ex) {
     throw ex;
   } catch (Exception ex) {
     throw new RuntimeException(
         "Could not search for TolvenPerson: " + principalLdapName + " in realm: " + realm + ": ",
         ex);
   }
   return searchResults;
 }
Exemplo n.º 3
0
  public boolean authenticate(String user, String pass) {
    String returnedAtts[] = {"sn", "givenName", "mail"};
    String searchFilter = "(&(objectClass=user)(sAMAccountName=" + user + "))";

    // Create the search controls
    SearchControls searchCtls = new SearchControls();
    searchCtls.setReturningAttributes(returnedAtts);

    // Specify the search scope
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapHost);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, user + "@" + domain);
    env.put(Context.SECURITY_CREDENTIALS, pass);

    LdapContext ctxGC = null;

    try {
      ctxGC = new InitialLdapContext(env, null);
      // Search objects in GC using filters
      NamingEnumeration answer = ctxGC.search(searchBase, searchFilter, searchCtls);
    } catch (NamingException ex) {
      // ex.printStackTrace();
      return false;
    }
    return true;
  }
  private User getUserBasicAttributes(String username, LdapContext ctx) {
    User user = null;
    try {

      SearchControls constraints = new SearchControls();
      constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
      String[] attrIDs = {"distinguishedName", "sn", "givenname", "mail", "telephonenumber"};
      constraints.setReturningAttributes(attrIDs);
      // First input parameter is search bas, it can be "CN=Users,DC=YourDomain,DC=com"
      // Second Attribute can be uid=username
      NamingEnumeration answer =
          ctx.search("DC=YourDomain,DC=com", "sAMAccountName=" + username, constraints);
      if (answer.hasMore()) {
        Attributes attrs = ((SearchResult) answer.next()).getAttributes();
        System.out.println("distinguishedName " + attrs.get("distinguishedName"));
        System.out.println("givenname " + attrs.get("givenname"));
        System.out.println("sn " + attrs.get("sn"));
        System.out.println("mail " + attrs.get("mail"));
      } else {
        throw new Exception("Invalid User");
      }

    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return user;
  }
  protected List<User> findUsersByGroupId(LdapUserQueryImpl query) {
    String baseDn = getDnForGroup(query.getGroupId());

    // compose group search filter
    String groupSearchFilter = "(& " + ldapConfiguration.getGroupSearchFilter() + ")";

    NamingEnumeration<SearchResult> enumeration = null;
    try {
      enumeration =
          initialContext.search(baseDn, groupSearchFilter, ldapConfiguration.getSearchControls());

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

      // first find group
      while (enumeration.hasMoreElements()) {
        SearchResult result = enumeration.nextElement();
        Attribute memberAttribute =
            result.getAttributes().get(ldapConfiguration.getGroupMemberAttribute());
        if (null != memberAttribute) {
          NamingEnumeration<?> allMembers = memberAttribute.getAll();

          // iterate group members
          while (allMembers.hasMoreElements() && groupMemberList.size() < query.getMaxResults()) {
            groupMemberList.add((String) allMembers.nextElement());
          }
        }
      }

      List<User> userList = new ArrayList<User>();
      String userBaseDn =
          composeDn(ldapConfiguration.getUserSearchBase(), ldapConfiguration.getBaseDn());
      for (String memberId : groupMemberList) {
        if (ldapConfiguration.isUsePosixGroups()) {
          query.userId(memberId);
        }
        List<User> users =
            ldapConfiguration.isUsePosixGroups()
                ? findUsersWithoutGroupId(query, userBaseDn)
                : findUsersWithoutGroupId(query, memberId);
        if (users.size() > 0) {
          userList.add(users.get(0));
        }
      }

      return userList;

    } catch (NamingException e) {
      throw new IdentityProviderException("Could not query for users", e);

    } finally {
      try {
        if (enumeration != null) {
          enumeration.close();
        }
      } catch (Exception e) {
        // ignore silently
      }
    }
  }
  /**
   * Search for entry that matches the specific <code>DirectoryQuery</code> conditions. Results will
   * be order using the values of a specific attribute
   *
   * @param q DirectoryQuery
   * @param attribute Name of the attribute that determines the order
   * @return java.util.List<DirectoryEntry>
   * @exception LDAPException
   */
  public List<Identity> sortedSearch(final LDAPDirectoryQuery q, final String attribute)
      throws LDAPException {
    TreeMap<String, Identity> results =
        new TreeMap<String, Identity>(Collator.getInstance(new Locale("es")));
    try {
      LdapContext ctx = connection.connect();
      if (ctx == null) {
        throw new LDAPException("Directory service not available");
      }
      SearchControls ctls = new SearchControls();
      if (connection.hasCountLimit()) {
        ctls.setCountLimit(connection.getCountLimit());
      }
      ctls.setSearchScope(connection.getScope());
      ctx.setRequestControls(new Control[] {new SortControl(attribute, Control.NONCRITICAL)});

      String filter = getQueryString(ctx, q);
      NamingEnumeration<SearchResult> answer = ctx.search(baseDN, filter, ctls);
      while (answer.hasMoreElements()) {
        SearchResult sr = answer.nextElement();
        LDAPDirectoryEntry _e = new LDAPDirectoryEntry(sr.getNameInNamespace());
        @SuppressWarnings("unchecked")
        NamingEnumeration<Attribute> ne =
            (NamingEnumeration<Attribute>) sr.getAttributes().getAll();
        while (ne.hasMore()) {
          Attribute att = ne.next();
          Object[] attrs = new Object[att.size()];
          @SuppressWarnings("unchecked")
          NamingEnumeration<Object> nea = (NamingEnumeration<Object>) att.getAll();
          for (int i = 0; nea.hasMore(); i++) {
            attrs[i] = nea.next();
          }
          _e.setAttribute(att.getID(), attrs);
        }
        String _value = String.valueOf(_e.getAttribute(attribute)[0]);
        while (results.containsKey(_value)) {
          _value = _value.concat("0");
        }
        results.put(_value, _e);
      }
    } catch (NullPointerException e) {
      _log.log(java.util.logging.Level.ALL, "sortedSearch() null pointer");
      throw new LDAPException("sorted search null pointer");
    } catch (NamingException e) {
      _log.log(java.util.logging.Level.ALL, "sortedSearch() - " + e.getMessage());
      throw new LDAPException(e.getMessage());
    } catch (IOException e) {
      _log.log(java.util.logging.Level.ALL, "sortedSearch() - " + e.getMessage());
      throw new LDAPException(e.getMessage());
    } finally {
      connection.disconnect();
    }
    return new ArrayList<Identity>(results.values());
  }
Exemplo n.º 7
0
  private boolean loginWithLDAP(String login, String password) {
    try {

      LdapContext context = null;
      try {
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.SECURITY_AUTHENTICATION, "Simple");
        env.put(Context.SECURITY_PRINCIPAL, login);
        //                env.put(Context.SECURITY_PRINCIPAL, "labs\\natalia.ukhorskaya");
        //                env.put(Context.SECURITY_CREDENTIALS, "DeeJou5d");
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put(Context.PROVIDER_URL, "ldap://msdc.labs.intellij.net:389");
        context = new InitialLdapContext(env, null);

      } catch (NamingException nex) {
        // nex.printStackTrace();
        return false;
      }

      String cn;
      if (login.contains("\\")) {
        cn = login.substring(login.indexOf("\\"));
      } else {
        cn = login;
      }

      String query = "(&(objectclass=person)(samaccountname=" + cn + "))";
      String attribute = "cn";

      SearchControls ctrl = new SearchControls();
      ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
      NamingEnumeration enumeration = context.search("dc=labs,dc=intellij,dc=net", query, ctrl);
      SearchResult result = (SearchResult) enumeration.next();
      if (result != null) {
        Attributes attribs = result.getAttributes();
        NamingEnumeration values = attribs.get(attribute).getAll();
        if (values.hasMore()) {
          userName = values.next().toString();
        }
        return true;
      }

    } catch (Throwable e) {
      // incorrect login or password
      ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(
          e, SessionInfo.TypeOfRequest.ANALYZE_LOG.name(), login + " " + password);
    }
    return false;
  }
  public List<Group> findGroupByQueryCriteria(LdapGroupQuery query) {
    ensureContextInitialized();

    String groupBaseDn =
        composeDn(ldapConfiguration.getGroupSearchBase(), ldapConfiguration.getBaseDn());

    if (ldapConfiguration.isSortControlSupported()) {
      applyRequestControls(query);
    }

    NamingEnumeration<SearchResult> enumeration = null;
    try {

      String filter = getGroupSearchFilter(query);
      enumeration =
          initialContext.search(groupBaseDn, filter, ldapConfiguration.getSearchControls());

      // perform client-side paging
      int resultCount = 0;
      List<Group> groupList = new ArrayList<Group>();
      while (enumeration.hasMoreElements() && groupList.size() < query.getMaxResults()) {
        SearchResult result = enumeration.nextElement();

        GroupEntity group = transformGroup(result);

        if (isAuthorized(READ, GROUP, group.getId())) {

          if (resultCount >= query.getFirstResult()) {
            groupList.add(group);
          }

          resultCount++;
        }
      }

      return groupList;

    } catch (NamingException e) {
      throw new IdentityProviderException("Could not query for users", e);

    } finally {
      try {
        if (enumeration != null) {
          enumeration.close();
        }
      } catch (Exception e) {
        // ignore silently
      }
    }
  }
  public List<User> findUsersWithoutGroupId(LdapUserQueryImpl query, String userBaseDn) {

    if (ldapConfiguration.isSortControlSupported()) {
      applyRequestControls(query);
    }

    NamingEnumeration<SearchResult> enumeration = null;
    try {

      String filter = getUserSearchFilter(query);
      enumeration =
          initialContext.search(userBaseDn, filter, ldapConfiguration.getSearchControls());

      // perform client-side paging
      int resultCount = 0;
      List<User> userList = new ArrayList<User>();
      while (enumeration.hasMoreElements() && userList.size() < query.getMaxResults()) {
        SearchResult result = enumeration.nextElement();

        UserEntity user = transformUser(result);

        if (isAuthenticatedUser(user) || isAuthorized(READ, USER, user.getId())) {

          if (resultCount >= query.getFirstResult()) {
            userList.add(user);
          }

          resultCount++;
        }
      }

      return userList;

    } catch (NamingException e) {
      throw new IdentityProviderException("Could not query for users", e);

    } finally {
      try {
        if (enumeration != null) {
          enumeration.close();
        }
      } catch (Exception e) {
        // ignore silently
      }
    }
  }
Exemplo n.º 10
0
  @Override
  protected AuthenticationInfo queryForAuthenticationInfo(
      AuthenticationToken token, LdapContextFactory contextFactory) throws NamingException {

    logger.debug(
        "queryForAuthenticationInfo, principal: {}, credentials: *****", token.getPrincipal());
    logger.debug("contextFactory : {}", contextFactory);

    try {
      if (token == null || token.getPrincipal() == null) {
        logger.info("No authentication token provided, will not try to authenticate..");
        return null;
      }

      LdapContext sysCtx = contextFactory.getSystemLdapContext();

      String objClsFilter = createObjectClassFilter(objectClasses);
      String userIdFilter = createAttributeFilter(userIdAttribute, token.getPrincipal().toString());

      String filter = mergeFiltersAND(objClsFilter, userIdFilter);

      NamingEnumeration<?> namingEnumeration =
          sysCtx.search(config.getUserLdapBaseDn(), filter, getSimpleSearchControls());

      while (namingEnumeration.hasMore()) {

        SearchResult result = (SearchResult) namingEnumeration.next();

        String dn = result.getNameInNamespace();

        try {
          contextFactory.getLdapContext(dn, token.getCredentials());

          return new SimpleAuthenticationInfo(dn, token.getCredentials(), "StaticRealm");

        } catch (Exception e) {
          logger.error(e.getMessage(), e);
        }
      }
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }

    return null;
  }
Exemplo n.º 11
0
  private NamingEnumeration search(LdapContext ctx, String searchValue) {
    SearchControls searchCtls = new SearchControls();

    // Specify the attributes to returned
    String returnedAtts[] = {dn};
    searchCtls.setReturningAttributes(returnedAtts);

    // Specify the search scope
    try {
      searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

      String searchFilter =
          "(&(objectClass=" + objectclass + ")(" + pkAttribute + "=" + searchValue + "))";

      log.debug("Search Filter=" + searchFilter);
      log.debug("BaseDN=" + this.baseDn);

      return ctx.search(baseDn, searchFilter, searchCtls);
    } catch (NamingException ne) {
      ne.printStackTrace();
    }
    return null;
  }
Exemplo n.º 12
0
  /**
   * Search for the user's entry. Determine the distinguished name of the user's entry and
   * optionally an authorization identity for the user.
   *
   * @param ctx an LDAP context to use for the search
   * @return the user's distinguished name or an empty string if none was found.
   * @exception LoginException if the user's entry cannot be found.
   */
  private String findUserDN(LdapContext ctx) throws LoginException {

    String userDN = "";

    // Locate the user's LDAP entry
    if (userFilter != null) {
      if (debug) {
        System.out.println(
            "\t\t[LdapLoginModule] " + "searching for entry belonging to user: "******"\t\t[LdapLoginModule] " + "cannot search for entry belonging to user: "******"Cannot find user's LDAP entry");
    }

    try {
      NamingEnumeration results =
          ctx.search("", replaceUsernameToken(filterMatcher, userFilter), constraints);

      // Extract the distinguished name of the user's entry
      // (Use the first entry if more than one is returned)
      if (results.hasMore()) {
        SearchResult entry = (SearchResult) results.next();

        // %%% - use the SearchResult.getNameInNamespace method
        //        available in JDK 1.5 and later.
        //        (can remove call to constraints.setReturningObjFlag)
        userDN = ((Context) entry.getObject()).getNameInNamespace();

        if (debug) {
          System.out.println("\t\t[LdapLoginModule] found entry: " + userDN);
        }

        // Extract a value from user's authorization identity attribute
        if (authzIdentityAttr != null) {
          Attribute attr = entry.getAttributes().get(authzIdentityAttr);
          if (attr != null) {
            Object val = attr.get();
            if (val instanceof String) {
              authzIdentity = (String) val;
            }
          }
        }

        results.close();

      } else {
        // Bad username
        if (debug) {
          System.out.println("\t\t[LdapLoginModule] user's entry " + "not found");
        }
      }

    } catch (NamingException e) {
      // ignore
    }

    if (userDN.equals("")) {
      throw (LoginException) new FailedLoginException("Cannot find user's LDAP entry");
    } else {
      return userDN;
    }
  }
  protected int authenticate(
      long companyId,
      long ldapServerId,
      String emailAddress,
      String screenName,
      long userId,
      String password)
      throws Exception {

    String postfix = LDAPSettingsUtil.getPropertyPostfix(ldapServerId);

    LdapContext ldapContext = PortalLDAPUtil.getContext(ldapServerId, companyId);

    if (ldapContext == null) {
      return FAILURE;
    }

    try {
      String baseDN = PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_BASE_DN + postfix);

      //  Process LDAP auth search filter

      String filter =
          LDAPSettingsUtil.getAuthSearchFilter(
              ldapServerId, companyId, emailAddress, screenName, String.valueOf(userId));

      Properties userMappings = LDAPSettingsUtil.getUserMappings(ldapServerId, companyId);

      String userMappingsScreenName =
          GetterUtil.getString(userMappings.getProperty("screenName")).toLowerCase();

      SearchControls searchControls =
          new SearchControls(
              SearchControls.SUBTREE_SCOPE,
              1,
              0,
              new String[] {userMappingsScreenName},
              false,
              false);

      NamingEnumeration<SearchResult> enu = ldapContext.search(baseDN, filter, searchControls);

      if (enu.hasMoreElements()) {
        if (_log.isDebugEnabled()) {
          _log.debug("Search filter returned at least one result");
        }

        SearchResult result = enu.nextElement();

        String fullUserDN = PortalLDAPUtil.getNameInNamespace(ldapServerId, companyId, result);

        Attributes attributes =
            PortalLDAPUtil.getUserAttributes(ldapServerId, companyId, ldapContext, fullUserDN);

        LDAPAuthResult ldapAuthResult = null;

        if (PropsValues.LDAP_IMPORT_USER_PASSWORD_ENABLED) {
          ldapAuthResult = authenticate(ldapContext, companyId, attributes, fullUserDN, password);

          // Process LDAP failure codes

          String errorMessage = ldapAuthResult.getErrorMessage();

          if (errorMessage != null) {
            if (errorMessage.indexOf(
                    PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_ERROR_USER_LOCKOUT))
                != -1) {

              throw new UserLockoutException();
            } else if (errorMessage.indexOf(
                    PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_ERROR_PASSWORD_EXPIRED))
                != -1) {

              throw new PasswordExpiredException();
            }
          }

          if (!ldapAuthResult.isAuthenticated() && PropsValues.LDAP_IMPORT_USER_PASSWORD_ENABLED) {

            return FAILURE;
          }
        }

        // Get user or create from LDAP

        User user =
            PortalLDAPImporterUtil.importLDAPUser(
                ldapServerId, companyId, ldapContext, attributes, password);

        // Process LDAP success codes

        if (ldapAuthResult != null) {
          String resultCode = ldapAuthResult.getResponseControl();

          if (resultCode.equals(LDAPAuth.RESULT_PASSWORD_RESET)) {
            UserLocalServiceUtil.updatePasswordReset(user.getUserId(), true);
          }
        }
      } else {
        if (_log.isDebugEnabled()) {
          _log.debug("Search filter did not return any results");
        }

        return DNE;
      }

      enu.close();
    } catch (Exception e) {
      if (e instanceof PasswordExpiredException || e instanceof UserLockoutException) {

        throw e;
      }

      _log.error("Problem accessing LDAP server", e);

      return FAILURE;
    } finally {
      if (ldapContext != null) {
        ldapContext.close();
      }
    }

    return SUCCESS;
  }
  public User importLDAPUser(
      long ldapServerId, long companyId, String emailAddress, String screenName) throws Exception {

    LdapContext ldapContext = null;

    NamingEnumeration<SearchResult> enu = null;

    try {
      String postfix = LDAPSettingsUtil.getPropertyPostfix(ldapServerId);

      String baseDN = PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_BASE_DN + postfix);

      ldapContext = PortalLDAPUtil.getContext(ldapServerId, companyId);

      if (ldapContext == null) {
        throw new SystemException("Failed to bind to the LDAP server");
      }

      String filter =
          PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_AUTH_SEARCH_FILTER + postfix);

      if (_log.isDebugEnabled()) {
        _log.debug("Search filter before transformation " + filter);
      }

      filter =
          StringUtil.replace(
              filter,
              new String[] {"@company_id@", "@email_address@", "@screen_name@"},
              new String[] {String.valueOf(companyId), emailAddress, screenName});

      if (_log.isDebugEnabled()) {
        _log.debug("Search filter after transformation " + filter);
      }

      Properties userMappings = LDAPSettingsUtil.getUserMappings(ldapServerId, companyId);

      String userMappingsScreenName =
          GetterUtil.getString(userMappings.getProperty("screenName")).toLowerCase();

      SearchControls searchControls =
          new SearchControls(
              SearchControls.SUBTREE_SCOPE,
              1,
              0,
              new String[] {userMappingsScreenName},
              false,
              false);

      enu = ldapContext.search(baseDN, filter, searchControls);

      if (enu.hasMoreElements()) {
        if (_log.isDebugEnabled()) {
          _log.debug("Search filter returned at least one result");
        }

        Binding binding = enu.nextElement();

        Attributes attributes =
            PortalLDAPUtil.getUserAttributes(
                ldapServerId,
                companyId,
                ldapContext,
                PortalLDAPUtil.getNameInNamespace(ldapServerId, companyId, binding));

        return importLDAPUser(ldapServerId, companyId, ldapContext, attributes, StringPool.BLANK);
      } else {
        return null;
      }
    } catch (Exception e) {
      if (_log.isWarnEnabled()) {
        _log.warn("Problem accessing LDAP server " + e.getMessage());
      }

      if (_log.isDebugEnabled()) {
        _log.debug(e, e);
      }

      throw new SystemException("Problem accessing LDAP server " + e.getMessage());
    } finally {
      if (enu != null) {
        enu.close();
      }

      if (ldapContext != null) {
        ldapContext.close();
      }
    }
  }
Exemplo n.º 15
0
  protected int authenticate(
      long ldapServerId,
      long companyId,
      String emailAddress,
      String screenName,
      long userId,
      String password)
      throws Exception {

    LdapContext ldapContext = _portalLDAP.getContext(ldapServerId, companyId);

    if (ldapContext == null) {
      return FAILURE;
    }

    NamingEnumeration<SearchResult> enu = null;

    try {
      LDAPServerConfiguration ldapServerConfiguration =
          _ldapServerConfigurationProvider.getConfiguration(companyId, ldapServerId);

      String baseDN = ldapServerConfiguration.baseDN();

      //  Process LDAP auth search filter

      String filter =
          _ldapSettings.getAuthSearchFilter(
              ldapServerId, companyId, emailAddress, screenName, String.valueOf(userId));

      Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId);

      String userMappingsScreenName = GetterUtil.getString(userMappings.getProperty("screenName"));

      userMappingsScreenName = StringUtil.toLowerCase(userMappingsScreenName);

      SearchControls searchControls =
          new SearchControls(
              SearchControls.SUBTREE_SCOPE,
              1,
              0,
              new String[] {userMappingsScreenName},
              false,
              false);

      enu = ldapContext.search(baseDN, filter, searchControls);

      if (enu.hasMoreElements()) {
        if (_log.isDebugEnabled()) {
          _log.debug("Search filter returned at least one result");
        }

        SearchResult result = enu.nextElement();

        String fullUserDN = _portalLDAP.getNameInNamespace(ldapServerId, companyId, result);

        Attributes attributes =
            _portalLDAP.getUserAttributes(ldapServerId, companyId, ldapContext, fullUserDN);

        // Get user or create from LDAP

        User user =
            _ldapUserImporter.importUser(
                ldapServerId, companyId, ldapContext, attributes, password);

        // Authenticate

        LDAPAuthResult ldapAuthResult =
            authenticate(ldapContext, companyId, attributes, fullUserDN, password);

        // Process LDAP failure codes

        String errorMessage = ldapAuthResult.getErrorMessage();

        if (errorMessage != null) {
          SystemLDAPConfiguration systemLDAPConfiguration =
              _systemLDAPConfigurationProvider.getConfiguration(companyId);

          int pos = errorMessage.indexOf(systemLDAPConfiguration.errorUserLockout());

          if (pos != -1) {
            throw new UserLockoutException.LDAPLockout(fullUserDN, errorMessage);
          }

          pos = errorMessage.indexOf(systemLDAPConfiguration.errorPasswordExpired());

          if (pos != -1) {
            throw new PasswordExpiredException();
          }
        }

        if (!ldapAuthResult.isAuthenticated()) {
          return FAILURE;
        }

        // Process LDAP success codes

        String resultCode = ldapAuthResult.getResponseControl();

        if (resultCode.equals(LDAPAuth.RESULT_PASSWORD_RESET)) {
          _userLocalService.updatePasswordReset(user.getUserId(), true);
        }
      } else {
        if (_log.isDebugEnabled()) {
          _log.debug("Search filter did not return any results");
        }

        return DNE;
      }
    } catch (Exception e) {
      if (e instanceof LDAPFilterException
          || e instanceof PasswordExpiredException
          || e instanceof UserLockoutException) {

        throw e;
      }

      _log.error("Problem accessing LDAP server", e);

      return FAILURE;
    } finally {
      if (enu != null) {
        enu.close();
      }

      if (ldapContext != null) {
        ldapContext.close();
      }
    }

    return SUCCESS;
  }
Exemplo n.º 16
0
  public static void main(String[] args) throws Exception {
    String server = "ldap://*****:*****@tql17ad.com";
    String password = "******";
    boolean ssl = false;

    Provider prov = null;

    if (ssl) {
      prov = Security.getProvider("com.sun.net.ssl.internal.ssl.Provider");

      if (prov == null) {
        Class moProviderClass = Class.forName("com.sun.net.ssl.internal.ssl.Provider");
        Provider moProvider = (Provider) moProviderClass.newInstance();
        Security.addProvider(moProvider);
      }
    }

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, server + rootCtx);
    env.put(Context.AUTHORITATIVE, "true");
    env.put(Context.SECURITY_PRINCIPAL, admin);
    env.put(Context.SECURITY_CREDENTIALS, password);

    if (ssl) {
      env.put(Context.SECURITY_PROTOCOL, "ssl");
    }

    // DirContext ctx = new InitialDirContext(env);
    LdapContext ctx = new InitialLdapContext(env, null);
    SearchControls searchCtls = new SearchControls();

    // Specify the attributes to return
    // String returnedAtts[] = { "name", "cn" };
    String returnedAtts[] = {"objectGUID", "cn", "whenChanged"};
    searchCtls.setReturningAttributes(returnedAtts);

    // Specify the search scope
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    int pageSize = 100;
    byte[] cookie = null;

    // ***************change************
    Control[] ctls = new Control[] {new PagedResultsControl(pageSize)};
    ctx.setRequestControls(ctls);
    // ***************change************

    int totalResults = 0;
    System.out.println("Initial context = " + ctx);

    do {
      NamingEnumeration nenum =
          ctx.search("", "(&(whenChanged>=19000101000000.0Z)(objectclass=group))", searchCtls);

      // loop through the results in each page
      while (nenum != null && nenum.hasMoreElements()) {
        SearchResult sr = (SearchResult) nenum.next();

        // print out the name
        System.out.println("name: " + sr.getName());
        // increment the counter
        totalResults++;
      }

      // examine the response controls
      cookie = parseControls(ctx.getResponseControls());

      System.out.println("cookie = " + cookie + " length = " + cookie.length);

      // pass the cookie back to the server for the next page
      ctx.setRequestControls(
          new Control[] {new PagedResultsControl(pageSize, cookie, Control.CRITICAL)});

    } while ((cookie != null) && (cookie.length != 0));

    ctx.close();
    System.out.println("Total entries: " + totalResults);

    // NamingEnumeration nenum = ctx.search("", "(objectclass=group)",
    // null);
    /*
     * NamingEnumeration nenum = ctx.search("", "(objectclass=group)",
     * searchCtls);
     *
     * int cnt = 0; for (NamingEnumeration ne = nenum; ne.hasMoreElements();
     * cnt++) { SearchResult sr = (SearchResult)ne.nextElement();
     * System.out.println(sr.getName()); }
     *
     * System.out.println(cnt);
     */
  }
    protected String getDNOfUser(
        String adminUser, String adminPassword, Context context, String netid) {
      // The resultant DN
      String resultDN;

      // The search scope to use (default to 0)
      int ldap_search_scope_value = 0;
      try {
        ldap_search_scope_value = Integer.parseInt(ldap_search_scope.trim());
      } catch (NumberFormatException e) {
        // Log the error if it has been set but is invalid
        if (ldap_search_scope != null) {
          log.warn(
              LogManager.getHeader(
                  context, "ldap_authentication", "invalid search scope: " + ldap_search_scope));
        }
      }

      // Set up environment for creating initial context
      Hashtable<String, String> env = new Hashtable<String, String>();
      env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
      env.put(javax.naming.Context.PROVIDER_URL, ldap_provider_url);

      LdapContext ctx = null;
      StartTlsResponse startTLSResponse = null;

      try {
        if ((adminUser != null)
            && (!adminUser.trim().equals(""))
            && (adminPassword != null)
            && (!adminPassword.trim().equals(""))) {
          if (useTLS) {
            ctx = new InitialLdapContext(env, null);
            // start TLS
            startTLSResponse = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());

            startTLSResponse.negotiate();

            // perform simple client authentication
            ctx.addToEnvironment(javax.naming.Context.SECURITY_AUTHENTICATION, "simple");
            ctx.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, adminUser);
            ctx.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS, adminPassword);
          } else {
            // Use admin credentials for search// Authenticate
            env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "simple");
            env.put(javax.naming.Context.SECURITY_PRINCIPAL, adminUser);
            env.put(javax.naming.Context.SECURITY_CREDENTIALS, adminPassword);

            // Create initial context
            ctx = new InitialLdapContext(env, null);
          }
        } else {
          // Use anonymous authentication
          env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "none");
        }

        Attributes matchAttrs = new BasicAttributes(true);
        matchAttrs.put(new BasicAttribute(ldap_id_field, netid));

        // look up attributes
        try {
          SearchControls ctrls = new SearchControls();
          ctrls.setSearchScope(ldap_search_scope_value);

          String searchName = "";
          if (useTLS) {
            searchName = ldap_search_context;
          } else {
            searchName = ldap_provider_url + ldap_search_context;
          }
          NamingEnumeration<SearchResult> answer =
              ctx.search(searchName, "(&({0}={1}))", new Object[] {ldap_id_field, netid}, ctrls);

          while (answer.hasMoreElements()) {
            SearchResult sr = answer.next();
            if (StringUtils.isEmpty(ldap_search_context)) {
              resultDN = sr.getName();
            } else {
              resultDN = (sr.getName() + "," + ldap_search_context);
            }

            String attlist[] = {
              ldap_email_field,
              ldap_givenname_field,
              ldap_surname_field,
              ldap_phone_field,
              ldap_group_field
            };
            Attributes atts = sr.getAttributes();
            Attribute att;

            if (attlist[0] != null) {
              att = atts.get(attlist[0]);
              if (att != null) {
                ldapEmail = (String) att.get();
              }
            }

            if (attlist[1] != null) {
              att = atts.get(attlist[1]);
              if (att != null) {
                ldapGivenName = (String) att.get();
              }
            }

            if (attlist[2] != null) {
              att = atts.get(attlist[2]);
              if (att != null) {
                ldapSurname = (String) att.get();
              }
            }

            if (attlist[3] != null) {
              att = atts.get(attlist[3]);
              if (att != null) {
                ldapPhone = (String) att.get();
              }
            }

            if (attlist[4] != null) {
              att = atts.get(attlist[4]);
              if (att != null) {
                ldapGroup = (String) att.get();
              }
            }

            if (answer.hasMoreElements()) {
              // Oh dear - more than one match
              // Ambiguous user, can't continue

            } else {
              log.debug(LogManager.getHeader(context, "got DN", resultDN));
              return resultDN;
            }
          }
        } catch (NamingException e) {
          // if the lookup fails go ahead and create a new record for them because the
          // authentication
          // succeeded
          log.warn(
              LogManager.getHeader(context, "ldap_attribute_lookup", "type=failed_search " + e));
        }
      } catch (NamingException | IOException e) {
        log.warn(LogManager.getHeader(context, "ldap_authentication", "type=failed_auth " + e));
      } finally {
        // Close the context when we're done
        try {
          if (startTLSResponse != null) {
            startTLSResponse.close();
          }
          if (ctx != null) {
            ctx.close();
          }
        } catch (NamingException | IOException e) {
        }
      }

      // No DN match found
      return null;
    }