【问题标题】:How to apply Spring Security AntMatchers pattern only to url with pathVariable如何仅将 Spring Security AntMatchers 模式应用于带有 pathVariable 的 url
【发布时间】:2019-09-15 17:01:46
【问题描述】:

我正在使用 Spring boot 和 WebSecurityConfigurerAdapter 来配置安全性。

配置忽略安全antMatches的方法如下:

    @Override
    public void configure(final WebSecurity web) {
        web
           .ignoring()
           .antMatchers("/items")
           .antMatchers("/items/{itemId}")

{itemId} 是 UUID 格式

问题在于,使用此配置,/items/report/items/images 等端点也会打开,但它们不应该打开。

有没有办法只对带有路径变量的uri应用忽略规则?

【问题讨论】:

  • 框架应该如何知道/items/report/items/images/items/{itemId} 之间的区别?它如何知道reportimages 不是/items/{itemId} 路由中itemId 的值?您必须首先为每个 not-allowed-value 声明一个限制,例如 /items/report/items/images,然后允许 /items/{itemId}
  • 对于其余的请求模式,你需要把authenicated,比如.antMatchers("/items/report").authenticated()

标签: java spring spring-boot spring-security


【解决方案1】:

你可以试试这个,d代表itemId

antMatchers("/items/{\\d+}").access("hasAnyAuthority('ROLE')")

如果你想全部许可

antMatchers("/items/**").permitAll()

【讨论】:

  • 你的回答没有那么有用,因为问题不是关于HttpSecurity,而是关于WebSecurity。没有像acesspermitAll 这样的方法。使用\d 假设 ID 是一个数字,但 OP 没有写任何关于 ID 格式的内容。
  • 将 ** 适用于任何数量的值,例如 "item/a/b/c" ??
【解决方案2】:

根据AntPathMarcher 的文档,您需要根据文档使用正则表达式指定路径变量:

{spring:[a-z]+} 匹配正则表达式 [a-z]+ 作为名为“spring”的路径变量。

你的情况是:

@Override
    public void configure(final WebSecurity web) {
        web
           .ignoring()
           .antMatchers("/items/{itemId:[\\d+]}")

【讨论】:

  • 你的答案是错误的,itemId 的格式是 UUID。更改您的 reqex 以改进您的答案。
  • 我认为只需要更改正则表达式。但是它只传递以 itemId 作为路径变量的路径的逻辑是正确的。所以@dur 你不能说这是错误的答案。可以轻松搜索 UUID 或任何其他模式的其余正则表达式。
  • 然后删除以开头的部分:这意味着你已经搜索了正确的reqex。
【解决方案3】:

要获得比 Ant 模式更复杂的匹配,请在控制器上使用基于方法的安全性或(更好的)服务层方法。

【讨论】:

  • 您的回答没有太大帮助,因为问题是关于 WebSecurity 并忽略 URL。如果使用方法安全,则不能忽略 URL,URL 必须经过过滤器链。
猜你喜欢
  • 2015-02-23
  • 2018-12-07
  • 2013-12-30
  • 2015-05-11
  • 2018-07-17
  • 1970-01-01
  • 1970-01-01
  • 2012-08-17
  • 2018-01-31
相关资源
最近更新 更多