0
spring security 4.1.3.RELEASE intercept-url request-matcher="mvc"

我尝试使用 spring-security.xml 来配置我的网络安全request-matche="mvc",但模式“/users/{userId:id}”不起作用。

我的配置看起来像下面的代码:

<http entry-point-ref="myAuthenticationEntryPoint" auto-config="true" use-expressions="true" create-session="stateless" request-matcher="mvc" 
      access-decision-manager-ref="myAccessDecisionManager">
    <intercept-url pattern="/users/{userId:\\d+}" method="GET" access="@webSecurity.isMe(authentication, #userId) or hasAnyRole('ADMIN')"/>
    <intercept-url pattern="/users/management" method="GET" access="hasAnyRole('ADMIN')"/>
</http>

我希望 /users/12345 的请求将匹配模式 /users/{userId:\d+},它将 12345 匹配到 userId,并且 /users/management 的请求将匹配模式 /users/management。然而,事实上,模式 /users/{userId:\d+} 不起作用,它永远不会匹配请求 /users/12345。如果我将设置更改为以下代码:

<http entry-point-ref="myAuthenticationEntryPoint" auto-config="true" use-expressions="true" create-session="stateless" request-matcher="mvc" 
      access-decision-manager-ref="myAccessDecisionManager">
    <intercept-url pattern="/users/{userId}" method="GET" access="@webSecurity.isMe(authentication, #userId) or hasAnyRole('ADMIN')"/>
    <intercept-url pattern="/users/management" method="GET" access="hasAnyRole('ADMIN')"/>
</http>

从 /users/{userId:\d+} 中删除 :\d+,它将匹配 /users/12345 的请求。但它也会匹配对 /users/management 的请求,这使得 userId 的值等于意外的“管理”。我尝试了 ant-matcher 和 regex-matcher,但在完美的解决方案中找不到 userId。

4

1 回答 1

0

我已经自己解决了这个问题。这是一个愚蠢的错误。为了解决这个问题,我只需要用 or 替换/users/{userId:\\d+}/users/{userId:\d+}使用/users/{userId:[0-9]+}AntPathMatcher 而不是使用 MvcPathMatcher。使用 spring-security.xml 配置安全性与使用 javaConfig 或使用注解不同。在javaConfig或者注解@RequestMapping中,里面的内容""是String Object,所以我们需要一个another\来转义\d+. 但在 xml 中,这是不必要的。如果\\d+在这里使用,spring security 会将其附加到\\\\d+,它永远不会匹配数字类型的字符串。当我设置断点org.springframework.util.AntPathMatcher.matchStrings(String str, Map<String, String> uriTemplateVariables)并观察请求时,我找到了这个解决方案。

于 2018-11-05T09:57:41.487 回答