Spring LdapTemplate 从组成员获取 SID

Spring LdapTemplate get SID from a group member

在一个地方,我 运行 一个查询给了我一个特定的组。

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

在我的映射器中:

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

问题是我有以下成员列表:

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

我只想得到他们的 SID,没有其他的。我不确定我该怎么做,因为它应该适用于不同的场景(因此变量 dn)。

我想避免如下丑陋的事情:

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;
    }

您应该使用 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());