【问题标题】:Spring security: How to make annotation based role specifications have precedence over pattern-based role specificationsSpring security:如何使基于注释的角色规范优先于基于模式的角色规范
【发布时间】:2018-03-10 22:58:40
【问题描述】:

我想结合基于角色的注释和基于模式的授权配置。

我希望基于模式的授权是“在未指定注释的情况下的回退”。

带注释的方法端点示例:

@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')")
@RequestMapping(
  method = RequestMethod.POST,
  headers = "Accept=application/json",
  path="publicApi/doWork" )
public void doWork() {
  ...
}

我的基于模式的授权配置如下:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
// specifies actuator endpoints should be secured by this config
@Order(ManagementServerProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  private void configureEndpointRoles(HttpSecurity http) throws Exception {
    http.authorizeRequests().
      antMatchers(anonymousUrlPatterns()).permitAll().
      antMatchers("/publicApi/**").access("hasAnyRole('ROLE_ADMIN')").
      anyRequest().denyAll();
    ;
  }
}

这是我想要的工作方式:

  • 如果端点 URL 匹配任何“anonymousUrlPatterns” - 允许。
  • 如果端点匹配“publicApi”模式并使用@PreAuthorize 进行注释,则使用注释中的定义来决定用户是否可以访问它(在这种情况下,用户需要 ADMIN 或 USER 角色)。李>
  • 如果端点与“publicApi”模式匹配但没有注释,则用户必须具有 ADMIN 角色才能访问它。
  • 如果端点不符合上述条件 - 拒绝。

我将如何定义这种行为?

按照指定的上述设置,基于模式的配置优先并且端点调用被拒绝(我不确定是基于模式的配置优先还是 Spring 是否以某种方式组合它们?)

春季版 - 4.2.3


更新:我已尝试将 EnableGlobalMethodSecurity 更新为:

@EnableGlobalMethodSecurity(
  prePostEnabled = true,
  order = Ordered.HIGHEST_PRECEDENCE)

但这似乎并没有改变行为。

【问题讨论】:

标签: spring spring-security


【解决方案1】:

根据@dur 的评论,您似乎无法使用基本配置来执行此操作。

在默认的 Spring Security AccessDecisionManager 策略下,来自基于模式的规则的“否”投票将导致整个调用被拒绝。

看起来我想要的行为将涉及编写一些自定义决策管理器逻辑,例如:http://www.baeldung.com/spring-security-custom-voter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 2017-10-19
    • 2020-12-18
    • 2016-10-14
    • 2023-04-05
    • 2019-06-15
    • 2020-06-16
    相关资源
    最近更新 更多