コード例 #1
0
ファイル: LDAPInitialConf.java プロジェクト: jaigates/IB
  /** Search criteria based on sn(surname) */
  private void searchUsingSubTree() {
    System.out.println("Inside searchUsingSubTree");
    DirContext ctx = LDAPConstants.getLdapContext();
    String baseDN = "OU=Staff,OU=Accounts,O=ibo,DC=adld,DC=ibo,DC=org";
    SearchControls sc = new SearchControls();
    String[] attributeFilter = {"cn", "givenName"};
    sc.setReturningAttributes(attributeFilter);
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = "sn=X*";
    // String filter = "(&(sn=R*)(givenName=Sinduja))";   //Examples for search Filters
    // String filter = "(|(sn=R*)(givenName=Sinduja))";

    NamingEnumeration results = null;
    try {
      results = ctx.search(baseDN, filter, sc);
      while (results.hasMore()) {
        SearchResult sr = (SearchResult) results.next();
        Attributes attrs = sr.getAttributes();

        Attribute attr = attrs.get("cn");
        System.out.print("cn : " + attr.get() + "\n");
        attr = attrs.get("givenName");
        System.out.print("givenName: " + attr.get() + "\n");
        ctx.close();
      }
    } catch (NamingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
コード例 #2
0
    private LdapEntry convertToLdapEntry(SearchResult searchResult, Attributes attributes)
        throws NamingException {
      String simpleName = null;
      String distinguishedName = null;

      if (groupNameAttribute != null) {
        SECURITY_LOGGER.tracef("Getting groupNameAttribute=%s", groupNameAttribute);
        Attribute groupNameAttr = attributes.get(groupNameAttribute);
        if (groupNameAttr != null) {
          simpleName = (String) groupNameAttr.get();
        }
      }

      if (groupDnAttribute != null) {
        if ("dn".equals(groupDnAttribute)) {
          SECURITY_LOGGER.trace("Obtaining dn using getNameInNamespace()");
          distinguishedName = searchResult.getNameInNamespace();
        } else {
          SECURITY_LOGGER.tracef("Getting groupDnAttribute=%s", groupDnAttribute);
          Attribute groupDnAttr = attributes.get(groupDnAttribute);
          if (groupDnAttr != null) {
            distinguishedName = (String) groupDnAttr.get();
          }
        }
      }

      return new LdapEntry(simpleName, distinguishedName);
    }
コード例 #3
0
  /**
   * Infer the root DN.
   *
   * @return null if not found.
   */
  private String inferRootDN(String server) {
    try {
      Hashtable<String, String> props = new Hashtable<String, String>();
      if (managerDN != null) {
        props.put(Context.SECURITY_PRINCIPAL, managerDN);
        props.put(Context.SECURITY_CREDENTIALS, getManagerPassword());
      }
      props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
      props.put(Context.PROVIDER_URL, toProviderUrl(fixNull(getServerUrl()), ""));

      DirContext ctx = new InitialDirContext(props);
      Attributes atts = ctx.getAttributes("");
      Attribute a = atts.get("defaultNamingContext");
      if (a != null
          && a.get()
              != null) { // this entry is available on Active Directory. See
                         // http://msdn2.microsoft.com/en-us/library/ms684291(VS.85).aspx
        return a.get().toString();
      }

      a = atts.get("namingcontexts");
      if (a == null) {
        LOGGER.warning("namingcontexts attribute not found in root DSE of " + server);
        return null;
      }
      return a.get().toString();
    } catch (NamingException e) {
      LOGGER.log(Level.WARNING, "Failed to connect to LDAP to infer Root DN for " + server, e);
      return null;
    }
  }
コード例 #4
0
  public Map<String, String> getAttributes(User user) throws DataSourceException, ConfigException {
    try {
      String s =
          "(&(objectClass="
              + source.getUsersObjectClassValue()
              + ")("
              + source.getUsersIdKey()
              + "="
              + user.getUid()
              + "))";
      List<SearchResult> r = this.search(s, SecurityEntityType.USER);
      if (!r.isEmpty()) {
        Attributes attrs = r.get(0).getAttributes();
        Map<String, String> items = new HashMap<String, String>();
        NamingEnumeration<? extends Attribute> lst = attrs.getAll();
        while (lst.hasMoreElements()) {
          Attribute attr = lst.nextElement();
          if (attr.get() != null) {
            items.put(attr.getID(), attr.get().toString());
          }
        }

        return items;
      } else {
        return null;
      }
    } catch (javax.naming.AuthenticationException e) {
      throw new ConfigException(e, "LDAP connection failed, please check your settings");
    } catch (NamingException e) {
      throw new DataSourceException(e, "LDAP Exception : " + e.getMessage());
    }
  }
コード例 #5
0
  /**
   * Retrieve the input attributes from the Active Directory for the given search query
   *
   * <p>Method getAttributes.
   *
   * @param searchBase String
   * @return List<User>
   * @throws NamingException
   */
  private final List<User> getAttributes(String searchBase) throws NamingException {
    LOGGER.info(">> getAttributes()");

    NamingEnumeration<SearchResult> results =
        localInitialLdapContext.search(searchBase, searchFilter, searchctls);

    List<User> users = new ArrayList<User>();
    User user = null;

    while (results.hasMoreElements()) {
      user = new User();
      SearchResult searchResult = results.next();
      Attributes attrs = searchResult.getAttributes();

      if (attrs != null && attrs.size() != 0) {
        Attribute attribute = null;

        String[] retrieveAttributes = parameters.getRetrieveAttributes();
        String[] attributesValues = new String[retrieveAttributes.length];
        for (int i = 0; i < retrieveAttributes.length; i++) {
          attribute = attrs.get(retrieveAttributes[i]);
          if (attribute != null && attribute.get() != null) {
            if (!isNullOrEmpty(attribute.get().toString())) {
              attributesValues[i] = attribute.get().toString();
            }
          }
        }
        user.setAttributeValues(attributesValues);
      }
      users.add(user);
    }

    LOGGER.info("<< getAttributes()");
    return users;
  }
コード例 #6
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    String param = request.getHeader("vector");
    if (param == null) param = "";

    String bar;

    // Simple ? condition that assigns constant to bar on true condition
    int num = 106;

    bar = (7 * 18) + num > 200 ? "This_should_always_happen" : param;

    org.owasp.benchmark.helpers.LDAPManager ads = new org.owasp.benchmark.helpers.LDAPManager();
    try {
      response.setContentType("text/html");
      String base = "ou=users,ou=system";
      javax.naming.directory.SearchControls sc = new javax.naming.directory.SearchControls();
      sc.setSearchScope(javax.naming.directory.SearchControls.SUBTREE_SCOPE);
      String filter = "(&(objectclass=person))(|(uid=" + bar + ")(street={0}))";
      Object[] filters = new Object[] {"The streetz 4 Ms bar"};

      javax.naming.directory.DirContext ctx = ads.getDirContext();
      javax.naming.directory.InitialDirContext idc = (javax.naming.directory.InitialDirContext) ctx;
      javax.naming.NamingEnumeration<javax.naming.directory.SearchResult> results =
          idc.search(base, filter, filters, sc);
      while (results.hasMore()) {
        javax.naming.directory.SearchResult sr =
            (javax.naming.directory.SearchResult) results.next();
        javax.naming.directory.Attributes attrs = sr.getAttributes();

        javax.naming.directory.Attribute attr = attrs.get("uid");
        javax.naming.directory.Attribute attr2 = attrs.get("street");
        if (attr != null) {
          response
              .getWriter()
              .write(
                  "LDAP query results:<br>"
                      + " Record found with name "
                      + attr.get()
                      + "<br>"
                      + "Address: "
                      + attr2.get()
                      + "<br>");
          System.out.println("record found " + attr.get());
        }
      }
    } catch (javax.naming.NamingException e) {
      throw new ServletException(e);
    } finally {
      try {
        ads.closeDirContext();
      } catch (Exception e) {
        throw new ServletException(e);
      }
    }
  }
コード例 #7
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    String param = request.getParameter("vector");
    if (param == null) param = "";

    String bar = doSomething(param);

    org.owasp.benchmark.helpers.LDAPManager ads = new org.owasp.benchmark.helpers.LDAPManager();
    try {
      response.setContentType("text/html");
      String base = "ou=users,ou=system";
      javax.naming.directory.SearchControls sc = new javax.naming.directory.SearchControls();
      sc.setSearchScope(javax.naming.directory.SearchControls.SUBTREE_SCOPE);
      String filter = "(&(objectclass=person)(uid=" + bar + "))";

      javax.naming.directory.DirContext ctx = ads.getDirContext();
      javax.naming.directory.InitialDirContext idc = (javax.naming.directory.InitialDirContext) ctx;
      javax.naming.NamingEnumeration<javax.naming.directory.SearchResult> results =
          idc.search(base, filter, sc);

      while (results.hasMore()) {
        javax.naming.directory.SearchResult sr =
            (javax.naming.directory.SearchResult) results.next();
        javax.naming.directory.Attributes attrs = sr.getAttributes();

        javax.naming.directory.Attribute attr = attrs.get("uid");
        javax.naming.directory.Attribute attr2 = attrs.get("street");
        if (attr != null) {
          response
              .getWriter()
              .write(
                  "LDAP query results:<br>"
                      + " Record found with name "
                      + attr.get()
                      + "<br>"
                      + "Address: "
                      + attr2.get()
                      + "<br>");
          System.out.println("record found " + attr.get());
        }
      }
    } catch (javax.naming.NamingException e) {
      throw new ServletException(e);
    } finally {
      try {
        ads.closeDirContext();
      } catch (Exception e) {
        throw new ServletException(e);
      }
    }
  } // end doPost
コード例 #8
0
  public Object mapFromAttributes(Attributes attributes) throws NamingException {
    BusinessUnitDTO contactDTO = new BusinessUnitDTO();
    Attribute commonName = attributes.get("cn");
    if (commonName != null) contactDTO.setCommonName((String) commonName.get());
    Attribute description = attributes.get("description");
    if (description != null) contactDTO.setDescription((String) description.get());
    Attribute displayName = attributes.get("displayName");
    if (displayName != null) contactDTO.setDisplayName((String) displayName.get());
    Attribute organization = attributes.get("o");
    if (organization != null) contactDTO.setOrganization((String) organization.get());

    return contactDTO;
  }
コード例 #9
0
ファイル: LDAPSearchImpl.java プロジェクト: jaigates/IB
  private Object getResults(Attribute attr, Object obj) {
    try {
      String name = attr.getID().toString();
      String Value = attr.get().toString();
      Class class1 = obj.getClass();
      String methodName =
          "set" + name.substring(0, 1).toUpperCase() + name.substring(1, name.length());
      String[] methodnameIgnot = {"-"};
      for (String ignore : methodnameIgnot) {
        methodName = methodName.replaceAll(ignore, "");
      }
      Method method = class1.getMethod(methodName, String.class);

      String value = (String) method.invoke(obj, Value);

    } catch (NamingException e) {
      e.printStackTrace();
    } catch (SecurityException e) {
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }
    return obj;
  }
コード例 #10
0
 /**
  * Seeds the bound instance's local ads-truststore with a set of instance key-pair public key
  * certificates. The result is the instance will trust any instance posessing the private key
  * corresponding to one of the public-key certificates. This trust is necessary at least to
  * initialize replication, which uses the trusted certificate entries in the ads-truststore for
  * server authentication.
  *
  * @param ctx The bound instance.
  * @param keyEntryMap The set of valid (i.e., not tagged as compromised) instance key-pair
  *     public-key certificate entries in ADS represented as a map from keyID to public-key
  *     certificate (binary).
  * @throws NamingException in case an error occurs while updating the instance's ads-truststore
  *     via LDAP.
  */
 public static void seedAdsTrustStore(InitialLdapContext ctx, Map<String, byte[]> keyEntryMap)
     throws NamingException {
   /* TODO: this DN is declared in some core constants file. Create a
   constants file for the installer and import it into the core. */
   final Attribute oc = new BasicAttribute("objectclass");
   oc.add("top");
   oc.add("ds-cfg-instance-key");
   for (Map.Entry<String, byte[]> keyEntry : keyEntryMap.entrySet()) {
     final BasicAttributes keyAttrs = new BasicAttributes();
     keyAttrs.put(oc);
     final Attribute rdnAttr =
         new BasicAttribute(
             ADSContext.ServerProperty.INSTANCE_KEY_ID.getAttributeName(), keyEntry.getKey());
     keyAttrs.put(rdnAttr);
     keyAttrs.put(
         new BasicAttribute(
             ADSContext.ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE.getAttributeName()
                 + ";binary",
             keyEntry.getValue()));
     final LdapName keyDn =
         new LdapName(
             (new StringBuilder(rdnAttr.getID()))
                 .append("=")
                 .append(Rdn.escapeValue(rdnAttr.get()))
                 .append(",")
                 .append(TRUSTSTORE_DN)
                 .toString());
     try {
       ctx.createSubcontext(keyDn, keyAttrs).close();
     } catch (NameAlreadyBoundException x) {
       ctx.destroySubcontext(keyDn);
       ctx.createSubcontext(keyDn, keyAttrs).close();
     }
   }
 }
コード例 #11
0
  private LdapUser looukupByFilter(String filter) {
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    DirContext ctxt;
    try {
      ctxt = connect();
      NamingEnumeration<SearchResult> results = ctxt.search(basedn, filter, sc);
      if (results.hasMore()) {
        SearchResult result = results.next();
        Attributes attrs = result.getAttributes();
        String firstName = attrs.get("givenName").get().toString();
        String lastName = attrs.get("sn").get().toString();
        String cn = attrs.get("cn").get().toString();
        String dn = result.getNameInNamespace();
        String forwardAddress = attrs.get("forward").get().toString();
        String mailAdress = attrs.get("mail").get().toString();
        Attribute addrAttr = attrs.get("privateMail");
        if (addrAttr == null) {
          addrAttr = attrs.get("forward");
        }
        String privateMailAdress = addrAttr.get().toString();

        LdapUser user =
            new LdapUser(
                dn, firstName, lastName, forwardAddress, mailAdress, privateMailAdress, cn);
        return user;
      }
    } catch (NamingException e) {
      log.fatal(e);
      throw new RuntimeException(e);
    }
    return null;
  }
コード例 #12
0
ファイル: LDAPUtil.java プロジェクト: Escobita/liferay-portal
  public static String[] getAttributeStringArray(Attributes attributes, String id)
      throws NamingException {

    if (Validator.isNull(id)) {
      return null;
    }

    Attribute attribute = attributes.get(id);

    if (attribute == null) {
      return new String[0];
    }

    int size = attribute.size();

    if (size == 0) {
      return null;
    }

    String[] array = new String[size];

    for (int i = 0; i < size; i++) {
      Object object = attribute.get(i);

      if (object == null) {
        array[i] = StringPool.BLANK;
      } else {
        array[i] = object.toString();
      }
    }

    return array;
  }
コード例 #13
0
  /** Return the last modified date. */
  @Override
  public long getLastModified() {

    if (!connected) {
      // Try to connect (silently)
      try {
        connect();
      } catch (IOException e) {
        // Ignore
      }
    }

    if (attributes == null) return 0;

    Attribute lastModified = attributes.get(ResourceAttributes.LAST_MODIFIED);
    if (lastModified != null) {
      try {
        Date lmDate = (Date) lastModified.get();
        return lmDate.getTime();
      } catch (Exception e) {
        // Ignore
      }
    }

    return 0;
  }
コード例 #14
0
  /**
   * @param attributes
   * @return
   * @throws NamingException
   */
  protected final Map<String, List<String>> convertToStringAttributesMap(Attributes attributes)
      throws NamingException {
    Map<String, List<String>> attributesMap = new HashMap<String, List<String>>();

    NamingEnumeration<String> attributeNames = attributes.getIDs();
    while (attributeNames.hasMore()) {
      String attributeName = attributeNames.next();
      if (ldapAttributesKey.getPasswordAttributeName().equalsIgnoreCase(attributeName)) {
        // skip
        continue;
      }
      Attribute attribute = attributes.get(attributeName);
      int numberOfValues = attribute.size();
      for (int i = 0; i < numberOfValues; i++) {
        String value = (String) attribute.get(i);
        if (null != value) {
          value = value.trim();
        }

        List<String> list = safeGetAttributeList(attributesMap, attributeName.toLowerCase());
        list.add(value);
      }
    }
    return attributesMap;
  }
  static boolean checkMatchingSearchResult(
      NamingEnumeration<SearchResult> result, String attrName, Object expValue)
      throws NamingException {
    while ((result != null) && result.hasMore()) {
      SearchResult sr = result.nextElement();
      Attributes attrs = sr.getAttributes();

      NamingEnumeration<? extends Attribute> attrVals = attrs.getAll();
      try {
        while ((attrVals != null) && attrVals.hasMore()) {
          Attribute a = attrVals.next();
          String attrID = a.getID();
          if (!attrName.equalsIgnoreCase(attrID)) {
            continue;
          }

          Object attrVal = a.get();
          if (expValue.equals(attrVal)) {
            return true;
          }
        }
      } finally {
        if (attrVals != null) {
          attrVals.close();
        }
      }
    }

    return false;
  }
コード例 #16
0
    @Override
    public LdapEntry[] groupSearch(DirContext dirContext, LdapEntry entry)
        throws IOException, NamingException {
      Set<LdapEntry> foundEntries = new HashSet<LdapEntry>();
      // Load the list of group.
      Attributes groups =
          dirContext.getAttributes(entry.getDistinguishedName(), new String[] {groupAttribute});
      Attribute groupRef = groups.get(groupAttribute);
      if (groupRef != null && groupRef.size() > 0) {
        NamingEnumeration<String> groupRefValues = (NamingEnumeration<String>) groupRef.getAll();
        while (groupRefValues.hasMore()) {
          String distingushedName = groupRefValues.next();
          SECURITY_LOGGER.tracef("Group found with distinguishedName=%s", distingushedName);
          String simpleName = null;
          if (groupNameAttribute != null) {
            // Load the Name
            Attributes groupNameAttrs =
                dirContext.getAttributes(distingushedName, new String[] {groupNameAttribute});
            Attribute groupNameAttr = groupNameAttrs.get(groupNameAttribute);
            simpleName = (String) groupNameAttr.get();
            SECURITY_LOGGER.tracef(
                "simpleName %s loaded for group with distinguishedName=%s",
                simpleName, distingushedName);
          } else {
            SECURITY_LOGGER.trace("No groupNameAttribute to load simpleName");
          }
          foundEntries.add(new LdapEntry(simpleName, distingushedName));
        }
      } else {
        SECURITY_LOGGER.tracef("No groups found for %s", entry);
      }

      return foundEntries.toArray(new LdapEntry[foundEntries.size()]);
    }
コード例 #17
0
ファイル: Service.java プロジェクト: am88tech/callhub
  public UserDTO doLdapAuthentication(UserDTO dto) throws Exception {
    log.info("INSIDE LDAP AUTHENTICATION 2");
    UserDTO ldapDTO = null;
    String url = "ldap://172.18.20.0:10389";
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "secret");

    try {
      ldapDTO = new UserDTO();
      DirContext ctx = new InitialDirContext(env);
      Attributes attrs = ctx.getAttributes("cn=" + dto.getUsername() + ",ou=users,ou=system");
      Attribute userPassword = attrs.get("userPassword");
      String ldapPasswordFromDB = new String((byte[]) userPassword.get());
      String md5EncryptedPassword = encryptLdapPassword("md5", dto.getPassword());
      if (md5EncryptedPassword.equalsIgnoreCase(ldapPasswordFromDB)) {
        ldapDTO.setEmployeeId((String) (attrs.get("employeeNumber").get()));
        ldapDTO.setEmployeeType((String) (attrs.get("employeeType").get()));
        ldapDTO.setUsername((String) (attrs.get("cn").get()));
      }
      ctx.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
    return ldapDTO;
  }
コード例 #18
0
  /** Returns the name of the specified header field. */
  @Override
  public String getHeaderField(String name) {

    if (!connected) {
      // Try to connect (silently)
      try {
        connect();
      } catch (IOException e) {
        // Ignore
      }
    }

    if (attributes == null) return (null);

    NamingEnumeration<String> attributeEnum = attributes.getIDs();
    try {
      while (attributeEnum.hasMore()) {
        String attributeID = attributeEnum.next();
        if (attributeID.equalsIgnoreCase(name)) {
          Attribute attribute = attributes.get(attributeID);
          if (attribute == null) return null;
          Object attrValue = attribute.get(attribute.size() - 1);
          return getHeaderValueAsString(attrValue);
        }
      }
    } catch (NamingException ne) {
      // Shouldn't happen
    }

    return (null);
  }
コード例 #19
0
  /**
   * Compare the given single value with the attribute value(s).
   *
   * @param val
   * @param that
   * @param ignoreCase
   * @return -2 for not equal or not present in multi-valued attribute -1 for val &lt; that 0 for
   *     val = that 1 for val &gt; that 2 for val present in multi-valued attr
   * @throws Throwable
   */
  public int attrValCompare(Object val, Attribute that, boolean ignoreCase) throws Throwable {
    if (that.size() != 1) {
      NamingEnumeration ne = that.getAll();

      if (ne == null) {
        return -2;
      }

      while (ne.hasMore()) {
        Object o = ne.next();
        if (val instanceof String) {
          if (compareVal(o, (String) val, ignoreCase) == 0) {
            return 2;
          }
        } else if (o.equals(val)) {
          return 2;
        }
      }
      return -2;
    }

    /** that is a single valued attribute. */
    Object o = that.get();

    if (val instanceof String) {
      return compareVal(o, (String) val, ignoreCase);
    }

    if (o.equals(val)) {
      return 0;
    }

    return -2;
  }
 private String getStringAttribute(Attributes user, String name) throws NamingException {
   Attribute a = user.get(name);
   if (a == null) return null;
   Object v = a.get();
   if (v == null) return null;
   return v.toString();
 }
コード例 #21
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));
    }
  }
コード例 #22
0
 public static String getIfNotNull(Attributes attrs, String attrID) throws NamingException {
   Attribute attr = attrs.get(attrID);
   if (attr != null) {
     return (String) attr.get();
   } else {
     return "";
   }
 }
コード例 #23
0
ファイル: UserLDAP.java プロジェクト: sucheng1980/suc_java
 // 得到属性
 private String getAttribute(Attributes attrs, String attrName) throws NamingException {
   Attribute attr = attrs.get(attrName);
   if (attr == null) {
     return "";
   } else {
     return (String) attr.get();
   }
 }
コード例 #24
0
 protected String getStringAttributeValue(String attrName, Attributes attributes)
     throws NamingException {
   Attribute attribute = attributes.get(attrName);
   if (attribute != null) {
     return (String) attribute.get();
   } else {
     return null;
   }
 }
コード例 #25
0
  /**
   * @see net.jforum.sso.LoginAuthenticator#validateLogin(java.lang.String, java.lang.String,
   *     java.util.Map)
   */
  public User validateLogin(String username, String password, Map extraParams) {
    Hashtable environment = this.prepareEnvironment();

    StringBuffer principal =
        new StringBuffer(256)
            .append(SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_PREFIX))
            .append(username)
            .append(',')
            .append(SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_SUFFIX));

    environment.put(Context.SECURITY_PRINCIPAL, principal.toString());
    environment.put(Context.SECURITY_CREDENTIALS, password);

    DirContext dir = null;

    try {
      dir = new InitialDirContext(environment);

      String lookupPrefix = SystemGlobals.getValue(ConfigKeys.LDAP_LOOKUP_PREFIX);
      String lookupSuffix = SystemGlobals.getValue(ConfigKeys.LDAP_LOOKUP_SUFFIX);

      if (lookupPrefix == null || lookupPrefix.length() == 0) {
        lookupPrefix = SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_PREFIX);
      }

      if (lookupSuffix == null || lookupSuffix.length() == 0) {
        lookupSuffix = SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_SUFFIX);
      }

      String lookupPrincipal = lookupPrefix + username + "," + lookupSuffix;

      Attribute att =
          dir.getAttributes(lookupPrincipal)
              .get(SystemGlobals.getValue(ConfigKeys.LDAP_FIELD_EMAIL));

      SSOUtils utils = new SSOUtils();

      if (!utils.userExists(username)) {
        String email = att != null ? (String) att.get() : "noemail";
        utils.register("ldap", email);
      }

      return utils.getUser();
    } catch (AuthenticationException e) {
      return null;
    } catch (NamingException e) {
      return null;
    } finally {
      if (dir != null) {
        try {
          dir.close();
        } catch (NamingException e) {
          // close jndi context
        }
      }
    }
  }
コード例 #26
0
  @Test
  public void testAttributeAccess() {
    final LdapName name =
        LdapUtils.createLdapName(
            IOC.getNodeTypeName(),
            "TestEcon2",
            COMPONENT.getNodeTypeName(),
            "TestEcom2",
            FACILITY.getNodeTypeName(),
            EFAN_NAME,
            UNIT.getNodeTypeName(),
            UNIT.getUnitTypeValue());

    try {
      Attributes attrs = LDAP_SERVICE.getAttributes(name);
      Assert.assertNotNull(attrs);
      Attribute attr = attrs.get(ATTR_FIELD_RESPONSIBLE_PERSON);
      Assert.assertNotNull(attr);
      String value = (String) attr.get();
      Assert.assertEquals("*****@*****.**", value);

      ModificationItem[] items =
          new ModificationItem[] {new ModificationItem(DirContext.REMOVE_ATTRIBUTE, attr)};
      LDAP_SERVICE.modifyAttributes(name, items);

      attrs = LDAP_SERVICE.getAttributes(name);
      Assert.assertNotNull(attrs);
      final Attribute attrNull = attrs.get(ATTR_FIELD_RESPONSIBLE_PERSON);
      Assert.assertNull(attrNull);

      items = new ModificationItem[] {new ModificationItem(DirContext.ADD_ATTRIBUTE, attr)};
      LDAP_SERVICE.modifyAttributes(name, items);

      attrs = LDAP_SERVICE.getAttributes(name);
      Assert.assertNotNull(attrs);
      attr = attrs.get(ATTR_FIELD_RESPONSIBLE_PERSON);
      Assert.assertNotNull(attr);
      value = (String) attr.get();
      Assert.assertEquals("*****@*****.**", value);

    } catch (final NamingException e) {
      Assert.fail("Unexpected Exception on attribute modification.");
    }
  }
コード例 #27
0
  /* Return all groups for principal == null or all groups for which principal
   * is a member
   *
   */
  private Collection<BwGroup> getGroups(
      final DirConfigProperties dirProps, final BwPrincipal principal) throws CalFacadeException {
    LdapConfigProperties props = (LdapConfigProperties) dirProps;
    InitialLdapContext ctx = null;
    String member = null;

    if (principal != null) {
      if (principal.getKind() == WhoDefs.whoTypeUser) {
        member = getUserEntryValue(props, principal);
      } else if (principal.getKind() == WhoDefs.whoTypeGroup) {
        member = getGroupEntryValue(props, principal);
      }
    }

    try {
      ctx = createLdapInitContext(props);

      BasicAttributes matchAttrs = new BasicAttributes(true);

      if (member != null) {
        matchAttrs.put(props.getGroupMemberAttr(), member);
      }

      String[] idAttr = {props.getGroupIdAttr()};

      ArrayList<BwGroup> groups = new ArrayList<BwGroup>();
      NamingEnumeration response = ctx.search(props.getGroupContextDn(), matchAttrs, idAttr);
      while (response.hasMore()) {
        SearchResult sr = (SearchResult) response.next();
        Attributes attrs = sr.getAttributes();

        Attribute nmAttr = attrs.get(props.getGroupIdAttr());
        if (nmAttr.size() != 1) {
          throw new CalFacadeException("org.bedework.ldap.groups.multiple.result");
        }

        BwGroup group = new BwGroup();
        group.setAccount(nmAttr.get(0).toString());
        group.setPrincipalRef(makePrincipalUri(group.getAccount(), WhoDefs.whoTypeGroup));

        groups.add(group);
      }

      return groups;
    } catch (Throwable t) {
      if (debug) {
        error(t);
      }
      throw new CalFacadeException(t);
    } finally {
      // Close the context to release the connection
      if (ctx != null) {
        closeContext(ctx);
      }
    }
  }
コード例 #28
0
 /**
  * Returns a Set with the String representation of the values of an attribute in a LDAP entry. The
  * returned Set will never be null.
  *
  * @param entry the entry.
  * @param attrName the attribute name.
  * @return a Set with the String representation of the values of an attribute in a LDAP entry.
  * @throws NamingException if there is an error processing the entry.
  */
 public static Set<String> getValues(SearchResult entry, String attrName) throws NamingException {
   Set<String> values = new HashSet<String>();
   Attributes attrs = entry.getAttributes();
   if (attrs != null) {
     Attribute attr = attrs.get(attrName);
     if (attr != null) {
       for (int i = 0; i < attr.size(); i++) {
         values.add((String) attr.get(i));
       }
     }
   }
   return values;
 }
コード例 #29
0
  /**
   * getAttrVal - return first (or only) value for given attribute "dn" is treated as an attribute
   * name.
   *
   * @param attr String attribute name
   * @return Object attribute value
   * @throws Throwable
   */
  public Object getAttrVal(String attr) throws Throwable {
    if (attr.equalsIgnoreCase("dn")) {
      return getDn();
    }

    Attribute a = findAttr(attr);

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

    return a.get();
  }
コード例 #30
0
 @Override
 protected Date buildLastLogonAttribute(Attribute lastLogonAttribute) throws NamingException {
   if (lastLogonAttribute != null) {
     for (int i = 0; i < lastLogonAttribute.size(); i++) {
       long date = Long.parseLong((String) lastLogonAttribute.get(i));
       if (date != 0L) {
         Date lastLogon = new Date(date / 10000 - WINDOWS_FILE_TIME_FORMAT_BASE_DATE);
         return lastLogon;
       }
     }
   }
   return null;
 }