Java 具有可变URL用户ID的antMatchers Spring安全模式
我找了很长时间的答案,但找不到任何有效的答案 在我的rest服务中,我在:/account/{id}/download下保留了一些功能,我想在SecurityConfig java文件中设置acces角色,只有保存了该角色的用户才能访问此url 当{id}是可变的时,模式应该是什么样子 我尝试了一些regexp模式,但没有任何效果,以下是我的一些尝试:Java 具有可变URL用户ID的antMatchers Spring安全模式,java,regex,spring,security,spring-security,Java,Regex,Spring,Security,Spring Security,我找了很长时间的答案,但找不到任何有效的答案 在我的rest服务中,我在:/account/{id}/download下保留了一些功能,我想在SecurityConfig java文件中设置acces角色,只有保存了该角色的用户才能访问此url 当{id}是可变的时,模式应该是什么样子 我尝试了一些regexp模式,但没有任何效果,以下是我的一些尝试: 1. antMatchers("account/**/download").access(somerolehere) 2. antMatcher
1. antMatchers("account/**/download").access(somerolehere)
2. antMatchers("account/\\d/download").access(somerolehere)
3. antMatchers("account/[\\d]/download").access(somerolehere)
提前感谢您的支持:)
编辑:
这对我很有用:
antMatchers("/account/{\\d+}/download").access("hasAnyAuthority('ROLE_TOKENSAVED')")
请注意表示ID的path变量周围的花括号。尽管Bohuslav的建议有效,但并不完整。根据AntPathMarcher的文档: 您需要使用正则表达式指定path变量:
{spring:[a-z]+}匹配regexp[a-z]+作为名为“spring”的路径变量。
如果不这样做,您可能会暴露其他路由。例如:
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/users/{^[\\d]$}").authenticated()
.antMatchers("/users/**").hasAuthority("admin")
以及UserController上的以下方法:
@ResponseBody
@RequestMapping(value = "/users/{userId}", method = RequestMethod.GET)
public User getUser(@PathVariable("userId") Object id) {
return userService.getUserById(userId);
}
@ResponseBody
@RequestMapping(value = "/users/roles", method = RequestMethod.GET)
public List<String> getAllRoles() {
return userService.getAllRoles();
}
如果path变量的名称是“accountId”是的,但只有在我注释.antMatchers(“/account*/**”)时才会起作用。access(“hasRole('ROLE\u USER')或hasRole('ROLE\u ADMIN'))模式,如何协调这两种模式?因为该匹配器更通用。匹配器必须从最特定到最不特定进行订购。所以把
/account/{\\d+}/download
匹配器放在它前面。但是为什么我要在模式中添加{}括号呢?因为控制器使用:{id}模式从中获取PathVariable?@azalut当您查看AntPathMatcher
JavaDoc时,它说:“URI模板变量是通过花括号(“{”和“}”)表示的。”。这只是Ant matchers的特定语法。请注意,\d
表示数值,我在路径中有字符串参数。因此,我使用了\w
。
@ResponseBody
@RequestMapping(value = "/users/{userId}", method = RequestMethod.GET)
public User getUser(@PathVariable("userId") Object id) {
return userService.getUserById(userId);
}
@ResponseBody
@RequestMapping(value = "/users/roles", method = RequestMethod.GET)
public List<String> getAllRoles() {
return userService.getAllRoles();
}
antMatchers("/account/{accountId:\\d+}/download")
.access("hasAnyAuthority('ROLE_TOKENSAVED')")