【问题标题】:How can I check what roles @PreAuthorize is looking at?如何检查 @PreAuthorize 正在查看的角色?
【发布时间】:2014-06-26 14:05:32
【问题描述】:

我有一些 Spring Controller 方法,起初我使用 @Secured 表示法进行保护

@Secured("Role_Admin")
public void dummyMethod(HttpServletRequest request) ...

如果用户没有该角色(如预期的那样),它将很好地识别角色,或者拒绝。但是,我尝试切换到使用 @PreAuthorize 注释,现在一切都被拒绝了。

@PreAuthorize("hasRole('Role_Admin')")
public void dummyMethod(HttpServletRequest request) ...

如果我删除 @PreAuthorize 注释,然后做某事,说

request.isUserInRole("Role_Admin")

这将返回 true。如果我留在注释中,然后检查用户的角色 在拒绝访问处理程序中,我可以看到授予用户“Role_Admin”权限。

所以我不确定@PreAuthorize 背后的代码正在检查哪些角色/权限。有人知道我可以检查哪些春季安全课程吗?

编辑

我正在使用 Java 来配置所有内容。所以它看起来像这样:

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfigurator extends GlobalMethodSecurityConfiguration { ...

在我对下面答案的回复中,我从 @Secured 切换的原因是因为它没有启动我的 AccessDeniedHandler。如果我可以强迫它这样做,我会坚持下去。 @PreAuthorize 确实启动了处理程序。

EDIT2

正如 Andrei 所指出的,我尝试在我的配置中定义它。但这并没有什么不同。

@Bean
public SimpleMappingExceptionResolver resolver() {
    SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();

    resolver.setExcludedExceptions(AccessDeniedException.class);

    Properties mappings = new Properties();
    mappings.put("org.springframework.web.servlet.PageNotFound", "p404");
    mappings.put("org.springframework.dao.DataAccessException", "dataAccessFailure");
    mappings.put("org.springframework.transaction.TransactionException", "dataAccessFailure");

    resolver.setExceptionMappings(mappings);

    return resolver;
}

【问题讨论】:

  • 您能发布您的安全配置 xml 吗?
  • 很可能,您已经看过this SO post,但我想我会分享它。
  • 看到了。我确实尝试在我的配置中添加一些东西,但是 ExceptionHandler 仍然会获取异常而不是 AccessDeniedHandler。将配置添加到问题中。

标签: java spring spring-security


【解决方案1】:

为什么要使用@PreAuthorize 而不是@Secured?我想您的 @PreAuthorize 失败了,因为您尚未将 http 安全设置为使用表达式:

<http use-expressions="true">

我想如果您这样做,那么您使用哪个版本都没有关系。我似乎记得其中一位在 SO 上发帖的 Spring 开发人员说 @Secured 是首选方法,因为它比 @PreAuthorize 或类似原因更新。我怀疑@Secured 更加独立,并且不与尽可能多的 Spring 组件交互。如果这不起作用,请告诉我。

【讨论】:

  • 当我使用 Secure 注释时,我的 AccessDeniedHandler 不会拾取拒绝访问异常。 PreAuthorize 注释确实将期望发送到处理程序。如果我可以让 Secure 注释启动 AccessDeniedHandler,那将是理想的。我尝试过的任何方法都没有奏效。我将在问题中发布我的配置。
  • 啊,好的。我有 90% 的把握,如果用户使用 @Secured 失败,您只需在不触及 AccessDeniedHandler 的情况下将 401 返回到浏览器。如果您想拦截 pre 或 post 句柄身份验证事件,请查看扩展 HandlerInterceptorAdapter
猜你喜欢
  • 1970-01-01
  • 2019-10-19
  • 1970-01-01
  • 2021-08-02
  • 2023-01-26
  • 1970-01-01
  • 2021-12-07
  • 2021-12-24
  • 1970-01-01
相关资源
最近更新 更多