【问题标题】:Are multiple roles allowed in the @Secured annotation with 'or' condition in Spring Security@Secured 注释中是否允许多个角色在 Spring Security 中具有“或”条件
【发布时间】:2016-08-21 21:19:43
【问题描述】:

我在我的项目中使用 spring 和 spring security 4。 我必须使用 ROLE_USER 或 ROLE_TIMER_TASK 调用我的 dao 方法。

目前我正在使用这个注解 -

 @Secured({"ROLE_USER", "ROLE_TIMER_TASK"})

此@Secured 注释只允许同时具有这两个角色的用户,但我想由具有任何一个角色的用户调用此方法。

如果用户具有此角色中的任何一个角色并调用此方法,是否有可能?

【问题讨论】:

  • 在我回答这个问题之后,我意识到 Secured 的默认行为是 or,尽管配置可以将其更改为 and。好吧,我想我的答案仍然有效。

标签: spring spring-mvc spring-security


【解决方案1】:

对于,请改用@PreAuthorize 注释:

@PreAuthorize("hasRole('ROLE_USER') or hasRole('ROLE_TIMER_TASK')")

在 Spring Security 版本 4 中,ROLE_ 前缀可以省略:

@PreAuthorize("hasRole('USER') or hasRole('TIMER_TASK')")

确保您在安全配置中启用了前注和后注。

【讨论】:

  • 感谢您提供此解决方案,但现在我面临另一个问题。当此安全方法调用其生成异常时 - org.springframework.security.authentication.ProviderNotFoundException: No AuthenticationProvider found for org.springframework.security.authentication.UsernamePasswordAuthenticationToken 我已使用 CAS 身份验证进行登录。那么我可以为这个异常做些什么呢?
  • @GouravSaklecha 似乎不相关,问一个新问题。
【解决方案2】:

要通过任何提到的角色调用方法,请使用:

@PreAuthorize("hasAnyRole('ROLE_USER','ROLE_TIMER_TASK')")

并在安全类中启用前后注释:

@EnableGlobalMethodSecurity(prePostEnabled = true)

【讨论】:

    【解决方案3】:

    除了holmis83之前的回答......

    为方法安全启用前置和后置注解:

    Java 配置:

    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class MethodSecurityConfig {
    // ...
    }
    

    Xml 配置:

    <global-method-security pre-post-annotations="enabled"/>
    

    【讨论】:

      猜你喜欢
      • 2011-12-16
      • 2015-05-30
      • 2017-05-28
      • 2021-09-27
      • 2016-08-11
      • 2016-01-03
      • 2021-10-04
      • 2016-07-18
      • 2017-05-18
      相关资源
      最近更新 更多