Spring LdapTemplate get SID from a group member

时间:2018-06-04 17:40:45

标签: spring-ldap

In one place I run a query that gives me a certain group.

LdapQuery groupQuery = LdapQueryBuilder.query().where("objectCategory").is("group").and("CN").is(groupCn);
List<String> userSids = groupLdapTemplate.search(groupQuery, mapper);

In the mapper I have:

public Object mapFromAttributes(Attributes attrs) throws NamingException {
        NamingEnumeration enumeration = attrs.get("member").getAll();
        (...)

The problem is that I have following list of members:

CN=S-1-5-21-1957455145-3106008588-2947984729-1106,CN=ForeignSecurityPrincipals,DC=mylab2,DC=local  
CN=S-1-5-21-1957455145-3106008588-2947984729-1105,CN=ForeignSecurityPrincipals,DC=mylab2,DC=local

I want to get just their SIDs without the rest. I am not sure how could I do that as it should be universal for different scenarios (thus variable dn).

I would like to avoid ugly things like below:

public Object mapFromAttributes(Attributes attrs) throws NamingException {
        List<String> result = new ArrayList<>();

        NamingEnumeration enumeration = attrs.get("member").getAll();

        while (enumeration.hasMoreElements()) {
            String value = (String) enumeration.nextElement();
            final String sidCn = value.split(",")[0];
            result.add(sidCn.substring(3, sidCn.length()));
        }

        return result;
    }

1 个答案:

答案 0 :(得分:1)

您应该使用ContextMapper来管理多个属性值,使用LdapUtils来解析可分辨名称:

ContextMapper<List<String>> mapper = new AbstractContextMapper<>() {
  public List<String> doMapFromContext(DirContextOperations ctx) {
    return Stream.of(ctx.getStringAttributes("member"))
                 .map(LdapUtils::newLdapName)
                 .map(name -> LdapUtils.getStringValue(name, name.size() - 1))
                 .collect(Collectors.toList());
    }
 };

 LdapQuery groupQuery = LdapQueryBuilder.query()
                          .where("objectCategory").is("group")
                          .and("CN").is(groupCn);
 List<String> userSids = groupLdapTemplate.search(groupQuery, mapper)
                          .stream()
                          .flatMap(Collection::stream)
                          .collect(Collectors.toList());