【问题标题】:Shiro JndiLdapRealm authorization against LDAPShiro JndiLdapRealm 针对 LDAP 的授权
【发布时间】:2012-08-23 19:13:37
【问题描述】:

JavaDoc for Shiro class JndiLdapRealm 明确表示默认情况下禁用授权,并且用户应通过继承和覆盖 JndiLdapRealm#doGetAuthorizationInfo 方法来实现对 LDAP 服务器的授权。 是否有关于如何做到这一点的示例代码,包括处理与任何地方可用的 LDAP 服务器的通信/协议?

【问题讨论】:

    标签: ldap shiro


    【解决方案1】:

    您应该实现自己的 LdapRealm 扩展 JndiLdapRealm。 在此实现中,您将覆盖 queryForAuthorizationInfo() ;这是一个简单的例子:

    protected AuthorizationInfo queryForAuthorizationInfo(PrincipalCollection principals, LdapContextFactory ldapContextFactory) throws NamingException {
    
    String username = (String) getAvailablePrincipal(principals);
    
    // Perform context search
    LdapContext ldapContext = ldapContextFactory.getSystemLdapContext();
    
    Set<String> roleNames;
    
    try {
      roleNames = getRoleNamesForUser(username, ldapContext);
    } finally {
      LdapUtils.closeContext(ldapContext);
    }
    
    return buildAuthorizationInfo(roleNames);
    }
    
    protected AuthorizationInfo buildAuthorizationInfo(Set<String> roleNames) {
    return new SimpleAuthorizationInfo(roleNames);
    }
    
    protected Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException {
    Set<String> roleNames;
    roleNames = new LinkedHashSet<String>();
    
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    
    //SHIRO-115 - prevent potential code injection:
    String searchFilter = "(&(objectClass=*)(CN={0}))";
    Object[] searchArguments = new Object[]{ username };
    
    NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls);
    
    while (answer.hasMoreElements()) {
      SearchResult sr = (SearchResult) answer.next();
    
      if (log.isDebugEnabled()) {
        log.debug("Retrieving group names for user [" + sr.getName() + "]");
      }
    
      Attributes attrs = sr.getAttributes();
    
      if (attrs != null) {
        NamingEnumeration ae = attrs.getAll();
        while (ae.hasMore()) {
          Attribute attr = (Attribute) ae.next();
    
          if (attr.getID().equals("memberOf")) {
    
            Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);
    
            if (log.isDebugEnabled()) {
              log.debug("Groups found for user [" + username + "]: " + groupNames);
            }
    
            Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
            roleNames.addAll(rolesForGroups);
          }
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-09-09
      • 2014-07-26
      • 2011-09-08
      • 2020-12-03
      • 2014-04-25
      • 2014-12-01
      • 2015-12-01
      • 2016-03-13
      • 2014-05-18
      相关资源
      最近更新 更多