2

采用此处提供的建议,我实现了自己的 RoleVoter 类,它扩展了 RoleVoter,我需要添加的额外检查是用户、角色和组织都根据我存储在会话中的组织排列。

我有以下 UserRole 类:

class UserRole implements Serializable {
  User user
  Role role
  Organization organization
  ....
}

这是我的 OrganizationRoleVoter 类:

class OrganizationRoleVoter extends RoleVoter {

  @Override
  public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {

    int result = ACCESS_ABSTAIN
    Collection<? extends GrantedAuthority> authorities = extractAuthorities(authentication)

    attributes.each {ConfigAttribute attribute ->
      if (this.supports(attribute)) {
        result = ACCESS_DENIED

        authorities.each {GrantedAuthority authority ->
          //TODO this should also check the chosen organization
          if (attribute.attribute.equals(authority.authority)) {
            return ACCESS_GRANTED
          }
        }
      }
    }
    return result
  }

  Collection<? extends GrantedAuthority> extractAuthorities(Authentication authentication) {
    return authentication.getAuthorities();
  }

}

正如您在我的 TODO 中看到的那样,这也是我需要说的“这里授予的权限也符合我在会议中放置的组织。真的不知道如何实现这一点。

4

1 回答 1

2

到目前为止,这是我解决它的方法。这似乎可行,但我总是愿意改进:

class OrganizationRoleVoter extends RoleVoter {

  @Override
  public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {

    int result = ACCESS_ABSTAIN
    Collection<? extends GrantedAuthority> authorities = extractAuthorities(authentication)
    GrailsWebRequest request = RequestContextHolder.currentRequestAttributes()
    Organization selectedOrganization = (Organization) request.session.getAttribute("selectedOrganizationSession")

    attributes.each {ConfigAttribute attribute ->
      if (this.supports(attribute)) {
        result = ACCESS_DENIED
        for (GrantedAuthority authority : authorities) {
          if (attribute.attribute.equals(authority.authority)) {
            def user = User.findByUsername(authentication.name)
            def role = Role.findByAuthority(authority.authority)
            if (UserRole.findByUserAndOrganizationAndRole(user, selectedOrganization, role)) {
              result = ACCESS_GRANTED
              break
            }
          }
        }
      }
    }
    return result
  }

  Collection<? extends GrantedAuthority> extractAuthorities(Authentication authentication) {
    return authentication.getAuthorities();
  }

}
于 2012-06-07T22:50:40.193 回答