【问题标题】:How to require multiple roles/authorities如何要求多个角色/权限
【发布时间】:2016-05-14 06:43:30
【问题描述】:

据我所知,@Secured 注释或 ExpressionUrlAuthorizationConfigurer 对象中只有 任何 列表可用。尝试添加多个注释或 hasAuthority() 调用要么编译失败,要么只使用最新的。

我如何定义特定请求(与模式匹配的一组请求)或方法需要所有角色/权限列表?

【问题讨论】:

  • hasAuthority() and hasAuthority() and hasAuthority() for @Securedaccess() 在使用 ExpressionUrlAuthorizationConfigurer 时。
  • 你的意思是@PreAuthorise,而不是@Secured
  • 问题在于无法添加到 SpEL 上下文中,因此您不能使用常量指定名称。
  • 嗯,不,但你为什么想要一个常数?
  • 为什么有人想要在常量的多个地方使用硬编码字符串?减少错误并提高可维护性。

标签: spring spring-security spring-4


【解决方案1】:

你可以像.hasAnyAuthority("manager", "customer");一样使用hasAnyAuthority

【讨论】:

    【解决方案2】:

    作为端点范围的解决方案,您可以使用

    .antMatchers("/user/**").access("hasAuthority('AUTHORITY_1') and hasAuthority('AUTHORITY_2')")
    

    我只用两个权威机构对其进行了测试,但我想你可以而且——不止两个。

    【讨论】:

      【解决方案3】:

      最好的解决办法似乎是

      @PreAuthorize("hasRole('one') and hasRole('two') and ...")
      

      没有很好的方式来使用常量,比如@Secured

      【讨论】:

      • 在我的项目中,我使用hasAuthority 而不是hasRole,这也适用于当局(只需更改权限的角色):@PreAuthorize("hasAuthority('one') and hasAuthority('two') and ...") 对于任何人都可以更改and or
      • @Ernani hasRole('x') <=> hasAuthority('ROLE_x')
      【解决方案4】:

      您似乎在使用:hasAuthority([authority])。这只需要一个权限。而是使用hasAnyAuthority([authority1,authority2])。这允许您一次指定多个权限,并且可以在授权中考虑任何权限。参考官方 spring 文档here。只需在页面中找到文本:hasAnyAuthority([authority1,authority2])

      例如在你的控制器方法上,添加:@PreAuthorize("hasAnyAuthority('permission1','permission2')")

      【讨论】:

      • 如问题所述,这是任何一个,而不是所有
      猜你喜欢
      • 2014-02-03
      • 1970-01-01
      • 1970-01-01
      • 2021-08-26
      • 2017-01-16
      • 1970-01-01
      • 2021-01-17
      • 2016-12-23
      • 1970-01-01
      相关资源
      最近更新 更多