首页 > 解决方案 > 通过检查 memberOf 过滤授予的权限

问题描述

如果它是重复的,我很抱歉,但我一直在努力解决这个话题。我需要过滤memberOf的搜索结果。我正在尝试将这些结果映射到Granted Authorities。我的解决方案基于此回购https://github.com/SNCF-SIV/spring-security-rest-jwt-ldap。下面的一段代码工作得很好:

@Bean
LdapAuthoritiesPopulator ldapAuthoritiesPopulator() throws Exception {

    class MyLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator {

        final SpringSecurityLdapTemplate ldapTemplate;
        public final String[] GROUP_ATTRIBUTE = {"cn"};
        public final String GROUP_MEMBER_OF = "memberof";

        MyLdapAuthoritiesPopulator(ContextSource contextSource) {
            ldapTemplate = new SpringSecurityLdapTemplate(contextSource);
        }

        @Override
        public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {

            String[] groupDns = userData.getStringAttributes(GROUP_MEMBER_OF);

            String roles = Stream.of(groupDns).map(groupDn -> {
                LdapName groupLdapName = (LdapName) ldapTemplate.retrieveEntry(groupDn, GROUP_ATTRIBUTE).getDn();

                return groupLdapName.getRdns().stream().map(Rdn::getValue).reduce((a, b) -> b).orElse(null);
            }).map(x -> (String)x).collect(Collectors.joining(","));

            return AuthorityUtils.commaSeparatedStringToAuthorityList(roles);
        }
    }

    return new MyLdapAuthoritiesPopulator(contextSource());
}

对于每个身份验证请求,它将用户的memberOf映射到他/她的authority。但它映射了用户所在的每个组。我想过滤它们,例如只获取以以下开头的组:
cn=ccms,cn=groups,o=company
它将返回组(并因此授予权限)
cn=test,cn=ccms,cn=groups,o=company,
cn=prod,cn=ccms,cn=groups,o=company
但不返回
cn=admins,cn=jira,cn=groups,o=company.

你能详细说明如何编写一个与上面的代码相匹配的简单过滤器吗?我有一种感觉,它是一个单线器。

编辑:我知道我可以轻松地比较字符串(比如只返回那些包含cn=ccms,cn=groups,o=company的字符串),但也许有更简洁的方法

标签: javaldapspring-security-ldap

解决方案


现在我已经通过添加:

    public final String GROUP_FILTER = "cn=ccms,cn=groups,o=company";

    final List<String> filteredGroupDns = Arrays.stream(groupDns)
                                                .filter(g -> g.toLowerCase().contains(GROUP_FILTER.toLowerCase()))
                                                .collect(Collectors.toList());

我还不会接受这个答案。我有更多与 LDAP 相关的解决方案(组搜索过滤器),请随时分享。


推荐阅读