【问题标题】:spring security: what's the best practice for include value in permission?spring security:在权限中包含值的最佳实践是什么?
【发布时间】:2021-03-22 15:17:50
【问题描述】:

在spring security或RBAC中,Authority被描述为一个字符串,例如“download-file”表示用户可以下载文件。如果我需要限制用户每日最大下载时间并为不同的用户分配不同的值,这意味着权限包含动态值,我该如何在 spring security 中做到这一点?

【问题讨论】:

    标签: spring-security permissions rbac authority


    【解决方案1】:

    请参考此链接 Spring Boot : Custom Role - Permission Authorization using SpEL

    您可以添加新权限,例如“DOWNLOAD_FILE”,如果当前用户具有该权限,则使用 -

    进行身份验证

    @PreAuthorize("hasPermission('DOWNLOAD_FILE')")

    您还可以限制角色的访问权限

    @PreAuthorize("hasRole('ADMIN') and hasPermission('DOWNLOAD_FILE')")

    【讨论】:

      【解决方案2】:

      正如您所暗示的那样,权限(即角色)和权限之间存在差异。权限倾向于广泛申请应用程序并且没有状态,而权限往往针对特定对象并包含状态。

      这似乎更像是域问题而不是权限问题。将逻辑放入安全性有点像拥有一个必须包含有效电子邮件的表单并在安全性中检查电子邮件格式。我会考虑将逻辑移到安全代码之外。

      如果你真的想用 Spring Security 做到这一点,我会使用一个自定义 Bean 来执行检查:

      @Component
      public class Download {
      
          public boolean isAlowedForUser(Authentication authentication) {
             // ...
             return result;
          }
      
          public boolean isAllowedForCurrentUser() {
             return isAllowedForUser(SecurityContextHolder.getContext().getAuthentiation());
          }
      }
      

      然后您可以将 Bean 自动装配到您的代码中,并通过调用代码检查权限。如果您愿意,您还可以集成到 Spring Security 的method security 来执行检查。要启用它,您需要在配置类之一的顶部指定@EnableGlobalMethodSecurity(prePostEnabled = true)。然后你可以在 Spring 托管的 Bean 上使用类似的东西:

      @PreAuthorize("@download.isAllowedForCurrentUser()")
      public void downloadFile(String fileName) {
      

      【讨论】:

      • 感谢您提供一种在 Spring-EL 中用于检查权限的方法。您提到了“权限,,, 包含状态”。据我所知,权限可以描述为“有”或“没有”,对于不同的用户不能描述为“有x值”,因此我认为权限是无状态的。对于我的问题,我正在设计一个数据结构,不仅用于弹簧安全性,还用于描述权限。一个目的是包含相同权限名称的动态值,例如。 “每天 x 次”的“下载文件”。我可以使用自定义代码来实现,但我正在寻找一种使用通用框架的方法。
      猜你喜欢
      • 2010-11-07
      • 2019-10-31
      • 2020-03-15
      • 2022-01-07
      • 2013-07-05
      • 1970-01-01
      • 2015-08-03
      • 2010-10-12
      • 2019-11-15
      相关资源
      最近更新 更多