【问题标题】:How to implement permission-based access control in Grails?如何在 Grails 中实现基于权限的访问控制?
【发布时间】:2012-05-04 16:26:13
【问题描述】:

我要实现基于权限的访问控制as discussed in this post。

我不熟悉实现 - 是否有任何详细示例说明如何从头到尾实现此功能?

【问题讨论】:

    标签: grails groovy permissions role


    【解决方案1】:

    你见过Spring security plugin吗? Main docs are here

    与this post 一样,您也可以考虑使用 Shiro 插件。我发现 Spring 安全插件更简单,但 Shiro 确实有一些优势,如帖子中所述。

    【讨论】:

    • 非常感谢您的帖子!实际上,我目前正在使用 spring security core 插件。我想做的是实现基于权限的访问控制,而不是基于角色的访问控制。但到目前为止,我还没有找到完全实现它的方法。
    • 抱歉,我看错了你的问题。一个有趣的帖子,我只能猜到你需要扩展基本的用户/角色域模型并实现一个自定义的 UserDetailsS​​ervice。似乎使事情复杂化,但如果你真的需要它,解决方案可能会很巧妙。
    • 非常感谢史蒂夫!您能否发布一个关于如何使用 UserDetailsS​​ervice 来解决我的问题的示例?这将是一个很大的帮助!谢谢!
    • 对不起,我没有示例,但我认为尝试关注客户 UserDetailsS​​ervice:grails-plugins.github.com/grails-spring-security-core/docs/… 并扩展使用 spring 安全插件提供的用户/角色域模型,以在您提供的链接中包含域类.现在如何将这些包含在注释或标记库中,编写自己的内容会很好,但您可以使用现有的基于规则的方法来执行此操作,请参阅:static.springsource.org/spring-security/site/docs/3.0.x/…
    【解决方案2】:

    我刚刚(大部分)解决了这个问题,所以我在这里发布以供参考。此解决方案适用于 Grails 2.2.4 和 Spring Security 2.0 RC

    1) 安全域模型 您按照文章中的描述为您的安全域类建模,因此您最终将拥有这些域: - 允许 - 角色 - 角色权限 - 用户 - 用户角色

    2) 查询用户权限 您确保您的 User 类返回 Permissions 而不是 Roles 作为 getAuthorities() 方法中的权限:

      /**
       * Gets authorities for the user.
       * 
       * It will return all of the Permissions of the User assigned by the Roles
       * which the User has
       */
      Set<Permission> getAuthorities() {
    
        Set allPermissions = []
        // Collect all Roles of the User
        UserRole.findAllByUser(this).each { userRole ->
          // Collect all Permissions from the Role  
          Role role = userRole.role
          // Returning the collected permissions
          RolePermission.findAllByRole(role).each { rp ->
            allPermissions.add(rp.permission)
          }
        }
        return allPermissions
      }
    

    3) Spring 安全配置

    我的 Config.groovy 中有这个用于 Spring Security 配置(不相关部分省略):

    grails {
      plugin {
        springsecurity {
          ...      
          userLookup {
            userDomainClassName = 'limes.security.User'
          }
          authority {
            nameField = 'name'
            className = 'limes.security.Permission'
          }
          ...
        }
      }
    }
    

    一个重要的亮点是 authority.nameField 必须符合您的 Permission 类。 name 属性在我的模型(和文章)中称为“name”。

    当然,您将 Permission 类设置为 authority.className 以使其符合 User.getAuthorities() 的返回值。

    4) 在安全表达式中使用

    上述方案并未解决 Grails Spring Security 插件只能使用以“ROLE_”开头的权限名称的限制。

    因此,如果您想调用“PERM_PERMISSION1”之类的权限,则必须在各处编写 EL 表达式进行检查(尤其是在控制器 @Secured 注释和静态 url 规则上)。

    所以不是

    @Secured(["PERM_PERMISSION1"])
    

    你写

    @Secured(["hasRole('PERM_PERMISSION1')"])
    

    【讨论】:

      猜你喜欢
      • 2016-07-26
      • 2019-04-24
      • 2023-04-06
      • 2020-12-12
      • 2013-10-31
      • 1970-01-01
      • 1970-01-01
      • 2012-12-06
      • 2020-02-28
      相关资源
      最近更新 更多