【问题标题】:How to obtain the 'reason'/cause for an AccessDeniedException in Spring Security?如何在 Spring Security 中获取 AccessDeniedException 的“原因”/原因?
【发布时间】:2012-10-26 17:53:06
【问题描述】:

我们正在使用具有方法级安全性的 Spring Security 3.1.3-RELEASE。效果很好。

我想登录,也许向用户展示,为什么他被拒绝访问。

使用org.springframework.security.web.access.AccessDeniedHandlerImpl 子类,我可以获得对抛出的org.springframework.security.access.AccessDeniedException 的引用,但我无法找到一种方法来确定导致它的原因(例如,“缺少角色ROLE_ADMIN”或类似的东西)。

是我遗漏了什么,还是根本不存在?

【问题讨论】:

  • 这里有同样的问题。如果 AccessDecisionVoters 不仅返回 ACCESS_GRANTED 或 ACCESS_DENIED 并且返回一个可以包含一个原因/原因的 AccessDeniedDecision 那就太好了
  • 我创建了一个 jira 问题:jira.springsource.org/browse/SEC-2148

标签: spring exception exception-handling spring-security


【解决方案1】:

不幸的是,Spring Security 中提供的默认实现是不可能的。

我研究了源代码并...

MethodSecurityInterceptor 负责保护方法调用。它将访问决策委托给AccessDecisionManager。 我检查了开箱即用的AccessDecisionManager 的每个实现。

  • 基于肯定的
  • 基于共识
  • 基于一致的

他们每个人都以类似的方式抛出AccessDeniedException异常。

case AccessDecisionVoter.ACCESS_DENIED:
                throw new AccessDeniedException(
                      messages.getMessage("AbstractAccessDecisionManager.accessDenied",
                      "Access is denied")
                 );

AbstractAccessDecisionManager.accessDenied是消息的名称,可以本地化。

英文是:

AbstractAccessDecisionManager.accessDenied=Access is denied

有几种开箱即用的语言,您可以自己制作翻译,但是...

仅此而已,没有关于异常原因的更多信息。

有关异常消息本地化的更多信息:

http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#localization

【讨论】:

    【解决方案2】:

    我还为此创建了一个 jira 问题:https://jira.spring.io/browse/SEC-3104

    @PreAuthorize, @PostAuthorize, @Secured 注释可以有一个参数来指向自定义消息属性,以便设置详细且对用户更友好的异常消息。

    这也可以通过提供一个参数来完成。定义一个扩展 AccessDeniedException 的类名,向您提出让用户处理其余部分。

    这样,同时处理复杂的规则,比如

    @PreAuthorize("record.createuser != authentication.getName()")

    我们可以得到一个定义的错误,例如

    "You cannot process a record that you created."" 等,而不是 "Access is denied"

    【讨论】:

      【解决方案3】:

      我已经实现了一个解决方案,它(仅)适用于 API 层中使用的授权注释(例如,使用 @RequestMapping)。在这里查看我的答案:https://stackoverflow.com/a/64846057/4413638

      【讨论】:

        猜你喜欢
        • 2016-01-31
        • 2021-12-09
        • 1970-01-01
        • 1970-01-01
        • 2016-07-01
        • 2021-08-09
        • 2010-09-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多