Shiro JndiLdapRealm authorization against LDAP

前端 未结 1 1632
梦谈多话
梦谈多话 2021-01-13 05:42

The JavaDoc for Shiro class JndiLdapRealm explicitly says that authorization is by default disabled and that authorization against an LDAP server should be implemented by th

1条回答
  •  [愿得一人]
    2021-01-13 06:22

    you should implement your own LdapRealm extending JndiLdapRealm. In this implementation, you would override queryForAuthorizationInfo() ; here is a simple example :

    protected AuthorizationInfo queryForAuthorizationInfo(PrincipalCollection principals, LdapContextFactory ldapContextFactory) throws NamingException {
    
    String username = (String) getAvailablePrincipal(principals);
    
    // Perform context search
    LdapContext ldapContext = ldapContextFactory.getSystemLdapContext();
    
    Set roleNames;
    
    try {
      roleNames = getRoleNamesForUser(username, ldapContext);
    } finally {
      LdapUtils.closeContext(ldapContext);
    }
    
    return buildAuthorizationInfo(roleNames);
    }
    
    protected AuthorizationInfo buildAuthorizationInfo(Set roleNames) {
    return new SimpleAuthorizationInfo(roleNames);
    }
    
    protected Set getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException {
    Set roleNames;
    roleNames = new LinkedHashSet();
    
    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 groupNames = LdapUtils.getAllAttributeValues(attr);
    
            if (log.isDebugEnabled()) {
              log.debug("Groups found for user [" + username + "]: " + groupNames);
            }
    
            Collection rolesForGroups = getRoleNamesForGroups(groupNames);
            roleNames.addAll(rolesForGroups);
          }
        }
      }
    }
    

    0 讨论(0)
提交回复
热议问题