简体   繁体   English

Java如何使用DN从ldap获取属性?

[英]Java how to get an Attribute from ldap using the DN?

I have a Java application that I use to search groups. 我有一个用于搜索组的Java应用程序。 It works pretty well with search based on the group name (cn) but sometimes I get more than one result since the same cn is used in other branches. 它基于组名(cn)进行搜索时效果很好,但是有时我会得到一个以上的结果,因为在其他分支中使用了相同的cn。 I have the DN of the group and I was wondering how to do a search based on the DN or if it's possible to access the attribute directly since I have the full path. 我有该组的DN,我想知道如何根据DN进行搜索,或者因为我有完整的路径,是否可以直接访问该属性。 Here is the code I use : 这是我使用的代码:

public Group getGroup( String groupName) throws Exception {

        List<User> memberList = new ArrayList<User>();

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

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

        // Specify the attributes to return
        String returnedAtts[] = { MEMBER_FIELD };

        searchCtls.setReturningAttributes( returnedAtts );

        // Specify the LDAP search filter
        String searchFilter = "(&(objectClass=group)(CN=" + groupName + "))";

        // Search for objects using the filter
        NamingEnumeration<SearchResult> answer = ctxMap.get( configMap.get( GROUP ) ).search( configMap.get( SEARCHBASE ), searchFilter,
                searchCtls );

        SearchResult sr = null;


        // Loop through the search results
        while ( answer.hasMoreElements() ) {
            sr = (SearchResult) answer.next();
        }
        if ( sr == null  ) {
            return group;
        }

        // Create an attribute for memberOf
        javax.naming.directory.Attribute member = sr.getAttributes().get( MEMBER_FIELD );

        // Enumeration of all elements in memberOf
        NamingEnumeration<?> ne = member.getAll();


        // Loop though the enumeration, cut unwanted characters and add all
        // elements to User List
        while ( ne.hasMoreElements() ) {
            ...
        }

    }

So I want to pass the group's distinguished name as parameter to the function instead of the group's name and have the search made on that or get the attributes directly. 因此,我想将组的专有名称作为参数而不是组的名称传递给函数,并对此进行搜索或直接获取属性。 Is this possible? 这可能吗?

PS: this code is used to get the members of a certain group. PS:此代码用于获取特定组的成员。

thank you 谢谢

You don't need to search if you have the DN. 如果您有DN,则无需搜索。 Just look it up, with lookup(). 只需使用lookup()进行查找。

With the help of EJP, I found out a way to get the attributes from the DistinguishedName without doing a search : 在EJP的帮助下,我找到了一种无需执行搜索即可从DistinguishedName获取属性的方法:

Attributes attrs;
attrs = ctx.getAttributes( dn );

Attribute attr= attrs.get( "the attribute you need" );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM