【问题标题】:Filter granted authorities by checking memberOf通过检查 memberOf 过滤授予的权限
【发布时间】:2021-07-24 16:39:12
【问题描述】:

很抱歉,如果它是重复的,但我一直在努力解决这个话题。我需要过滤 memberOf 的搜索结果。我正在尝试将这些结果映射到 Granted Authorities。我的解决方案基于此 repo 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 映射到他/她的权限。但它会映射用户所在的每个组。我想过滤它们,例如只获取以以下开头的组:
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 的字符串),但也许有更简洁的方法

【问题讨论】:

    标签: java ldap spring-security-ldap


    【解决方案1】:

    现在我已经通过添加:

        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 相关的解决方案(组搜索过滤器),请随时分享。

    【讨论】:

      猜你喜欢
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 2014-10-06
      • 1970-01-01
      • 1970-01-01
      • 2015-05-17
      相关资源
      最近更新 更多