自定义RoleVoter和访问UserRole以进行额外的投票检查

时间:2012-06-07 21:00:18

标签: grails spring-security

根据here提供的建议,我实现了自己的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中所看到的,我还需要说“在这里授予的权限也与我在会话中放置的组织一致。真的不知道怎么样实现这一目标。

1 个答案:

答案 0 :(得分: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();
  }

}