Ejemplo n.º 1
0
  @Test
  public void testUpdateArray() throws Exception {
    String sql =
        "update LdapModel.People set userid = 1, vals = ('a','b') where dn = 'x'"; //$NON-NLS-1$

    QueryMetadataInterface metadata = exampleLdap();

    Update query = (Update) getCommand(sql, metadata);

    LDAPExecutionFactory config = new LDAPExecutionFactory();

    LdapContext context = Mockito.mock(LdapContext.class);

    Mockito.stub(context.lookup("")).toReturn(context);

    LDAPUpdateExecution lue = new LDAPUpdateExecution(query, context);

    lue.execute();
    ArgumentCaptor<ModificationItem[]> captor = ArgumentCaptor.forClass(ModificationItem[].class);
    Mockito.verify(context)
        .modifyAttributes(ArgumentCaptor.forClass(String.class).capture(), captor.capture());
    ModificationItem[] modifications = captor.getValue();
    assertEquals(2, modifications.length);
    assertEquals("uid: 1", modifications[0].getAttribute().toString());
    assertEquals("vals: a, b", modifications[1].getAttribute().toString());
  }
  public User importLDAPUserByScreenName(long companyId, String screenName) throws Exception {

    long ldapServerId = PortalLDAPUtil.getLdapServerId(companyId, screenName, StringPool.BLANK);

    SearchResult result =
        (SearchResult)
            PortalLDAPUtil.getUser(ldapServerId, companyId, screenName, StringPool.BLANK);

    if (result == null) {
      if (_log.isWarnEnabled()) {
        _log.warn("No user was found in LDAP with screenName " + screenName);
      }

      return null;
    }

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

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

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

    User user = importLDAPUser(ldapServerId, companyId, ldapContext, attributes, StringPool.BLANK);

    ldapContext.close();

    return user;
  }
Ejemplo n.º 3
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));
    }
  }
Ejemplo n.º 4
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;
  }
  /**
   * Get the existing RequestControls from the LdapContext, call {@link #createRequestControl()} to
   * get a new instance, build a new array of Controls and set it on the LdapContext.
   *
   * <p>The {@link Control} feature is specific for LDAP v3 and thus applies only to {@link
   * LdapContext}. However, the generic DirContextProcessor mechanism used for calling <code>
   * preProcess</code> and <code>postProcess</code> uses DirContext, since it also works for LDAP
   * v2. This is the reason that DirContext has to be cast to a LdapContext.
   *
   * @param ctx an LdapContext instance.
   * @throws NamingException
   * @throws IllegalArgumentException if the supplied DirContext is not an LdapContext.
   */
  public void preProcess(DirContext ctx) throws NamingException {
    LdapContext ldapContext;
    if (ctx instanceof LdapContext) {
      ldapContext = (LdapContext) ctx;
    } else {
      throw new IllegalArgumentException(
          "Request Control operations require LDAPv3 - " + "Context must be of type LdapContext");
    }

    Control[] requestControls = ldapContext.getRequestControls();
    if (requestControls == null) {
      requestControls = new Control[0];
    }
    Control newControl = createRequestControl();

    Control[] newControls = new Control[requestControls.length + 1];
    for (int i = 0; i < requestControls.length; i++) {
      if (replaceSameControlEnabled && requestControls[i].getClass() == newControl.getClass()) {
        log.debug("Replacing already existing control in context: " + newControl);
        requestControls[i] = newControl;
        ldapContext.setRequestControls(requestControls);
        return;
      }
      newControls[i] = requestControls[i];
    }

    // Add the new Control at the end of the array.
    newControls[newControls.length - 1] = newControl;

    ldapContext.setRequestControls(newControls);
  }
    private ProxyLdapContext(Hashtable env) throws NamingException {
      final Map<String, Object> savedEnv = new HashMap<String, Object>();
      for (final String key :
          Arrays.asList(
              Context.SECURITY_AUTHENTICATION,
              Context.SECURITY_CREDENTIALS,
              Context.SECURITY_PRINCIPAL,
              Context.SECURITY_PROTOCOL)) {
        final Object entry = env.remove(key);
        if (entry != null) {
          savedEnv.put(key, entry);
        }
      }
      delegate = new InitialLdapContext(env, null);
      tls = (StartTlsResponse) delegate.extendedOperation(new StartTlsRequest());
      tls.setHostnameVerifier(
          new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
              return true;
            }
          });
      try {
        final SSLSession negotiate = tls.negotiate();
        Logger.getLogger(this.getClass().getCanonicalName())
            .fine("LDAP is now using " + negotiate.getProtocol());
      } catch (final IOException e) {
        throw new NamingException(e.getMessage());
      }
      for (final Map.Entry<String, Object> savedEntry : savedEnv.entrySet()) {
        delegate.addToEnvironment(savedEntry.getKey(), savedEntry.getValue());
      }
    }
Ejemplo n.º 7
0
 public static void main(String[] args) {
   try {
     LdapContext ctx = ActiveDirectory.getConnection("lcevallosc", "Passw0rd");
     System.out.println("Aqui tooyyy me longoneee");
     ctx.close();
   } catch (Exception e) {
     // Failed to authenticate user!
     e.printStackTrace();
   }
 }
    /** contact the ldap server and attempt to authenticate */
    protected boolean ldapAuthenticate(String netid, String password, Context context) {
      if (!password.equals("")) {

        LdapContext ctx = null;
        StartTlsResponse startTLSResponse = null;

        // 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);

        try {
          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, netid);
            ctx.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS, password);
            ctx.addToEnvironment(javax.naming.Context.AUTHORITATIVE, "true");
            ctx.addToEnvironment(javax.naming.Context.REFERRAL, "follow");
            // dummy operation to check if authentication has succeeded
            ctx.getAttributes("");
          } else if (!useTLS) {
            // Authenticate
            env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "Simple");
            env.put(javax.naming.Context.SECURITY_PRINCIPAL, netid);
            env.put(javax.naming.Context.SECURITY_CREDENTIALS, password);
            env.put(javax.naming.Context.AUTHORITATIVE, "true");
            env.put(javax.naming.Context.REFERRAL, "follow");

            // Try to bind
            ctx = new InitialLdapContext(env, null);
          }
        } catch (NamingException | IOException e) {
          // something went wrong (like wrong password) so return false
          log.warn(LogManager.getHeader(context, "ldap_authentication", "type=failed_auth " + e));
          return false;
        } finally {
          // Close the context when we're done
          try {
            if (startTLSResponse != null) {
              startTLSResponse.close();
            }
            if (ctx != null) {
              ctx.close();
            }
          } catch (NamingException | IOException e) {
          }
        }
      } else {
        return false;
      }

      return true;
    }
  /**
   * 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());
  }
  public void importFromLDAP(long ldapServerId, long companyId) throws Exception {

    if (!LDAPSettingsUtil.isImportEnabled(companyId)) {
      return;
    }

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

    if (ldapContext == null) {
      return;
    }

    try {
      Properties userMappings = LDAPSettingsUtil.getUserMappings(ldapServerId, companyId);
      Properties userExpandoMappings =
          LDAPSettingsUtil.getUserExpandoMappings(ldapServerId, companyId);
      Properties contactMappings = LDAPSettingsUtil.getContactMappings(ldapServerId, companyId);
      Properties contactExpandoMappings =
          LDAPSettingsUtil.getContactExpandoMappings(ldapServerId, companyId);
      Properties groupMappings = LDAPSettingsUtil.getGroupMappings(ldapServerId, companyId);

      String importMethod = PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_IMPORT_METHOD);

      if (importMethod.equals(_IMPORT_BY_GROUP)) {
        importFromLDAPByGroup(
            ldapServerId,
            companyId,
            ldapContext,
            userMappings,
            userExpandoMappings,
            contactMappings,
            contactExpandoMappings,
            groupMappings);
      } else if (importMethod.equals(_IMPORT_BY_USER)) {
        importFromLDAPByUser(
            ldapServerId,
            companyId,
            ldapContext,
            userMappings,
            userExpandoMappings,
            contactMappings,
            contactExpandoMappings,
            groupMappings);
      }
    } catch (Exception e) {
      _log.error("Error importing LDAP users and groups", e);
    } finally {
      if (ldapContext != null) {
        ldapContext.close();
      }
    }
  }
Ejemplo n.º 11
0
 @Override
 public LdapContext getLdapContext(Object principal, Object credentials) throws NamingException {
   LdapContext ctx = getSystemLdapContext();
   ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, principal);
   ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials);
   try {
     // AUTHENTICATE CREDENTIALS BY CREATING AN INITIAL LDAP CONTEXT
     new InitialLdapContext(ctx.getEnvironment(), null);
   } catch (AuthenticationException ex) {
     throw new AuthenticationException("Access denied: " + principal);
   }
   return ctx;
 }
Ejemplo n.º 12
0
  /**
   * Method authenticate.
   *
   * @param username String
   * @param password String
   * @return boolean * @throws Exception
   */
  public boolean authenticate(String username, String password) throws Exception {
    try {
      ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, username);
      ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
      ctx.reconnect(connCtls);
    } catch (AuthenticationException e) {
      throw e;
    } catch (NamingException e) {
      throw e;
    }

    return true;
  }
Ejemplo n.º 13
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;
  }
Ejemplo n.º 14
0
 private void checkPasswordUsingBind(
     LdapContextFactory ldapContextFactory, String user, String pass)
     throws AuthenticationException {
   LdapContext ctx = null;
   try {
     ctx = ldapContextFactory.getLdapContext(user, pass);
     ctx.getAttributes("");
   } catch (javax.naming.AuthenticationException e) {
     throw new AuthenticationException("User '" + user + "' cannot be authenticated.", e);
   } catch (NamingException e) {
     throw new AuthenticationException("User '" + user + "' cannot be authenticated.", e);
   } finally {
     LdapUtils.closeContext(ctx);
   }
 }
Ejemplo n.º 15
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;
 }
  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;
  }
Ejemplo n.º 17
0
  // GHH 20080326 - set all batches as last batch after an exception
  // is thrown calling a method on the enumeration.  Per Javadoc for
  // javax.naming.NamingEnumeration, enumeration is invalid after an
  // exception is thrown - by setting last batch indicator we prevent
  // it from being used again.
  // GHH 20080326 - also added return of explanation for generic
  // NamingException
  public List<?> next() throws TranslatorException {
    try {
      if (unwrapIterator != null) {
        if (unwrapIterator.hasNext()) {
          return unwrapIterator.next();
        }
        unwrapIterator = null;
      }
      // The search has been executed, so process up to one batch of
      // results.
      List<?> result = null;
      while (result == null && searchEnumeration != null && searchEnumeration.hasMore()) {
        SearchResult searchResult = (SearchResult) searchEnumeration.next();
        try {
          result = getRow(searchResult);
        } catch (InvalidNameException e) {

        }
      }

      if (result == null && this.executionFactory.usePagination()) {
        byte[] cookie = null;
        Control[] controls = ldapCtx.getResponseControls();
        if (controls != null) {
          for (int i = 0; i < controls.length; i++) {
            if (controls[i] instanceof PagedResultsResponseControl) {
              PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
              cookie = prrc.getCookie();
            }
          }
        }

        if (cookie == null) {
          return null;
        }

        setRequestControls(cookie);
        executeSearch();
        return next();
      }

      if (result != null) {
        resultCount++;
      }
      return result;
    } catch (SizeLimitExceededException e) {
      if (resultCount != searchDetails.getCountLimit()) {
        String msg = LDAPPlugin.Util.gs(LDAPPlugin.Event.TEIID12008);
        TranslatorException te = new TranslatorException(e, msg);
        if (executionFactory.isExceptionOnSizeLimitExceeded()) {
          throw te;
        }
        this.executionContext.addWarning(te);
        LogManager.logWarning(LogConstants.CTX_CONNECTOR, e, msg);
      }
      return null; // GHH 20080326 - if size limit exceeded don't try to read more results
    } catch (NamingException ne) {
      throw new TranslatorException(ne, LDAPPlugin.Util.gs("ldap_error")); // $NON-NLS-1$
    }
  }
  @SuppressWarnings("rawtypes")
  protected void applyRequestControls(AbstractQuery query) {

    try {
      List<Control> controls = new ArrayList<Control>();

      String orderBy = query.getOrderBy();
      if (orderBy != null) {
        orderBy = orderBy.substring(0, orderBy.length() - 4);
        if (UserQueryProperty.USER_ID.getName().equals(orderBy)) {
          controls.add(new SortControl(ldapConfiguration.getUserIdAttribute(), Control.CRITICAL));

        } else if (UserQueryProperty.EMAIL.getName().equals(orderBy)) {
          controls.add(
              new SortControl(ldapConfiguration.getUserEmailAttribute(), Control.CRITICAL));

        } else if (UserQueryProperty.FIRST_NAME.getName().equals(orderBy)) {
          controls.add(
              new SortControl(ldapConfiguration.getUserFirstnameAttribute(), Control.CRITICAL));

        } else if (UserQueryProperty.LAST_NAME.getName().equals(orderBy)) {
          controls.add(
              new SortControl(ldapConfiguration.getUserLastnameAttribute(), Control.CRITICAL));
        }
      }

      initialContext.setRequestControls(controls.toArray(new Control[0]));

    } catch (Exception e) {
      throw new IdentityProviderException("Exception while setting paging settings", e);
    }
  }
Ejemplo n.º 19
0
 /**
  * Method finito.
  *
  * @throws Exception
  */
 public void finito() throws Exception {
   try {
     if (ctx != null) ctx.close();
   } catch (NamingException e) {
     throw e;
   }
 }
  protected void applyRequestControls(AbstractQuery<?, ?> query) {

    try {
      List<Control> controls = new ArrayList<Control>();

      List<QueryOrderingProperty> orderBy = query.getOrderingProperties();
      if (orderBy != null) {
        for (QueryOrderingProperty orderingProperty : orderBy) {
          String propertyName = orderingProperty.getQueryProperty().getName();
          if (UserQueryProperty.USER_ID.getName().equals(propertyName)) {
            controls.add(new SortControl(ldapConfiguration.getUserIdAttribute(), Control.CRITICAL));

          } else if (UserQueryProperty.EMAIL.getName().equals(propertyName)) {
            controls.add(
                new SortControl(ldapConfiguration.getUserEmailAttribute(), Control.CRITICAL));

          } else if (UserQueryProperty.FIRST_NAME.getName().equals(propertyName)) {
            controls.add(
                new SortControl(ldapConfiguration.getUserFirstnameAttribute(), Control.CRITICAL));

          } else if (UserQueryProperty.LAST_NAME.getName().equals(propertyName)) {
            controls.add(
                new SortControl(ldapConfiguration.getUserLastnameAttribute(), Control.CRITICAL));
          }
        }
      }

      initialContext.setRequestControls(controls.toArray(new Control[0]));

    } catch (Exception e) {
      throw new IdentityProviderException("Exception while setting paging settings", e);
    }
  }
  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
      }
    }
  }
Ejemplo n.º 22
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;
  }
Ejemplo n.º 23
0
 private void close(LdapContext ctx, String realm) {
   try {
     if (ctx != null) {
       ctx.close();
     }
   } catch (Exception ex) {
     throw new RuntimeException("Could not close ldap context for realm: " + realm, ex);
   }
 }
 public void close() {
   if (initialContext != null) {
     try {
       initialContext.close();
     } catch (Exception e) {
       // ignore
       LOG.log(Level.FINE, "exception while closing LDAP DIR CTX", e);
     }
   }
 }
Ejemplo n.º 25
0
 @Override
 public LdapContext getSystemLdapContext() throws NamingException {
   try {
     InitialLdapContext ictx = new InitialLdapContext();
     LdapContext ctx = (LdapContext) ictx.lookup(getLdapJndi());
     /* Glassfish does not pass through these properties, even though it is aware of them?
      * Without com.sun.jndi.ldap.LdapCtxFactory, authentication is NOT carried out
      */
     ctx.addToEnvironment(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
     ctx.addToEnvironment("java.naming.ldap.attributes.binary", "userPKCS12");
     if (logger.isDebugEnabled()) {
       String providerURL = (String) ctx.getEnvironment().get(Context.PROVIDER_URL);
       logger.debug("LDAP providerURL=" + providerURL);
     }
     return ctx;
   } catch (Exception ex) {
     throw new RuntimeException("Failed to lookup " + getLdapJndi(), ex);
   }
 }
Ejemplo n.º 26
0
 public boolean closeLdap(LdapContext ldatCtx) {
   try {
     logger.debug(" start close ldap context ... ");
     ldatCtx.close();
     logger.debug(" close ldap context success. ");
     return true;
   } catch (NamingException e) {
     logger.error(" close ldap context failed. ", e);
     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
      }
    }
  }
Ejemplo n.º 29
0
 // GHH 20080326 - replaced existing implementation with the same
 // code as used by cancel method.  First try to
 // close the searchEnumeration, then the search context
 // We are very conservative when closing the enumeration
 // but less so when closing context, since it is safe to call close
 // on contexts multiple times
 @Override
 public void close() {
   if (searchEnumeration != null) {
     try {
       searchEnumeration.close();
     } catch (Exception e) {
     } // catch everything, because NamingEnumeration has undefined behavior if it previously hit
       // an exception
   }
   if (ldapCtx != null) {
     try {
       ldapCtx.close();
     } catch (NamingException ne) {
       LogManager.logWarning(
           LogConstants.CTX_CONNECTOR,
           LDAPPlugin.Util.gs(LDAPPlugin.Event.TEIID12003, ne.getExplanation()));
     }
   }
 }
Ejemplo n.º 30
0
  /** Clean out state because of a failed authentication attempt */
  private void cleanState() {
    username = null;
    if (password != null) {
      Arrays.fill(password, ' ');
      password = null;
    }
    try {
      if (ctx != null) {
        ctx.close();
      }
    } catch (NamingException e) {
      // ignore
    }
    ctx = null;

    if (clearPass) {
      sharedState.remove(USERNAME_KEY);
      sharedState.remove(PASSWORD_KEY);
    }
  }