【问题标题】:When should we use @PreAuthorize and @Secured我们什么时候应该使用@PreAuthorize 和@Secured
【发布时间】:2015-04-23 06:55:45
【问题描述】:

我阅读了这篇 stackoverflow 帖子 What's the difference between @Secured and @PreAuthorize in spring security 3? 但是,我仍然不清楚两者在安全性方面的最大区别是什么?与@Secured 相比,我们应该在哪些情况下使用@PreAuthorize?

【问题讨论】:

    标签: java spring spring-security annotations spring-annotations


    【解决方案1】:

    @PreAuthorize 允许您对规则进行更细粒度的控制以保护 o 方法。您可以在其中使用 SpEL 表达式。

    使用@Secured 保护方法会得到与@PreAuthorize 相同的结果,但@Secured 是有限的,并且您没有太多选项来调整规则(粗略的简化,规则是“静态的” ")。

    Spring Security 3.0 引入了使用 Spring EL 表达式作为授权机制的能力,以及之前见过的简单使用配置属性和访问决策投票器的能力。基于表达式的访问控制建立在相同的架构上,但允许将复杂的布尔逻辑封装在单个表达式中。

    【讨论】:

    • 因此,就安全功能而言,如果我将 @Secured("hasRole('ROLE_ADMIN')") 替换为 @PreAuthorize("hasRole('ROLE_ADMIN')") 没有区别。跨度>
    • @Zack:您不能将hasRole@Secured 一起使用。你只能说@Secured({"ROLE_ADMIN"})hasRole 表示使用 SpEL 执行方法。 @Secured 不支持 SpEL。
    【解决方案2】:

    @PreAuthorize是较新的版本,因此您应该始终使用@PreAuthorize,由于here提到的原因,确实更好。

    事实上

    @Secured("ROLE_ADMIN") 等同于@PreAuthorize("hasRole('ROLE_ADMIN')")

    此外,@PreAuthorize 语法更具可读性。

    例如 @Secured({"ROLE_USER", "ROLE_ADMIN"}) 被视为 ROLE_USER or ROLE_ADMIN,这很奇怪和令人困惑。

    @PreAuthorize 的另一边,您使用“Spring 表达式语言 (SpEL)”,在其中明确定义 orand 表达式,这显然更方便且更具可读性。

    所以选择@PreAuthorize

    【讨论】:

    • 那么,如果 OR 是默认设置,如何在 Secured annotations 中指定 AND 逻辑
    猜你喜欢
    • 2021-09-07
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 2017-09-13
    • 2021-12-29
    相关资源
    最近更新 更多