我想在Active Directory中使用sAMaccountName搜索用户,其中sAMaccountName为firstName.substring(0,1)+ lastName +以任意数字结尾。
代码段:

 try {
      context=this.getADConnection();

      String returnedAtts[]={"givenName","sn"};
      String sAMAccountNameRegex=sAMAccountName+"\\d*";
      //String sAMAccountNameRegex=sAMAccountName+Pattern.quote("[0-9]*");
      SearchControls searchControls = new SearchControls();
  searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
  searchControls.setReturningAttributes(returnedAtts);
  searchControls.setReturningAttributes(returnedAtts);
  searchControls.setReturningAttributes(returnedAtts);
  //String searchFilter = "(&(objectClass=user)(givenName=" +firstInitial+"*)(sn="+lastName+"))";
  String searchFilter = "(&(objectClass=user) (|(&(givenName=" +firstInitial+"*)(sn="+lastName+"))(sAMAccountName=("+sAMAccountNameRegex+"))) )";
  logger.info(className + privateMethodName + "  Searching User using filter : [" + searchFilter + "]");
  // Search for objects using the filter
  // Search for objects using the filter
      NamingEnumeration<SearchResult> results = context.search(SAMAccountNamePrePop.adSearchBase, searchFilter, searchControls);
      SearchResult searchResult = null;
      while(results.hasMoreElements()) {
      searchResult = (SearchResult) results.nextElement();
      logger.info(className + privateMethodName + " Search Result : [" + searchResult + "]");
      totalResults++;
      }`


使用的搜索过滤器是

String searchFilter = "(&(objectClass=user) (|(&(givenName=" +firstInitial+"*)(sn="+lastName+"))(sAMAccountName=("+sAMAccountNameRegex+"))) )";

我已经尝试使用以下搜索过滤器来搜索sAMaccountName,但没有一个起作用,并给出以下异常


String sAMAccountNameRegex=sAMaccountName.Pattern.quote("\\d*");

Exception is: [invalid escape sequence: [B@755c9b9c]

传递值后,searchfileter如下所示:


[(&(objectClass=user) (|(&(givenName=C*)(sn=BOND3))(sAMAccountName=(CBOND3\Q\d*\E))) )]


字符串sAMAccountNameRegex = sAMAccountName +“([0-9] *)$”;

Exception is:[[LDAP: error code 32 - 0000208D: NameErr: DSID-031001E5, problem 2001 (NO_OBJECT), data 0, best match of: '']]

after passing values searchfileter looks like:

[(&(objectClass=user) (|(&(givenName=C*)(sn=BOND3))(sAMAccountName=(CBOND3([0-9]*)$))) )]
字符串sAMAccountNameRegex = sAMAccountName +“ \ d *”;

Exception:[[LDAP: error code 32 - 0000208D: NameErr: DSID-031001E5, problem 2001 (NO_OBJECT), data 0, best match of: '']]

after passing values searchfileter looks like:


[(&(objectClass=user) (|(&(givenName=C*)(sn=BOND3))(sAMAccountName=(CBOND3\d*))) )]

那么是否可以查询Ldap,其中searchfilter是字符串和正则表达式的组合?

最佳答案

这是我尝试过的方法及其工作方式:

我正在使用sAMaccountName *查询活动目录,我得到了用户,然后在本地代码中处理了regex操作

Attributes attrs = ((SearchResult) answer.next());
String userId=attrs.get("sAMAccountNAme").toString();
if(userId.matches(sAMAccountNameRegex)){
    //business logic goes here
}

10-02 01:38