具有可变URL用户ID的java antMatchers Spring安全模式
我找了很长时间的答案,但找不到任何有效的答案
在我的rest服务中,我在:/account/{id}/download下保留了一些功能,我想在SecurityConfig java文件中设置acces角色,只有保存了该角色的用户才能访问此url
当{id}是可变的时,模式应该是什么样子
我尝试了一些regexp模式,但没有任何效果,以下是我的一些尝试:
1. antMatchers("account/**/download").access(somerolehere)
2. antMatchers("account/\\d/download").access(somerolehere)
3. antMatchers("account/[\\d]/download").access(somerolehere)
提前感谢您的支持:)
编辑:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin**").access("hasRole('ROLE_ADMIN')")
.antMatchers("/account*//**").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
.antMatchers("/account/\\d+/download").access("hasRole('ROLE_TOKENSAVED')")
.antMatchers("/user**").permitAll()
//othercode...
}
# 1 楼答案
这对我很有用:
请注意,在表示ID的path变量周围有一个大括号
# 2 楼答案
尽管博胡斯拉夫的建议有效,但并不完整。根据AntPathMarcher的文档: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/AntPathMatcher.html
您需要使用正则表达式指定path变量:
{spring:[a-z]+} matches the regexp [a-z]+ as a path variable named "spring"
如果不这样做,您可能会暴露其他路由。例如:
以及UserController上的以下方法:
因为您没有指定路径变量
userId
,所以用户可以在没有管理权限的情况下对“/users/roles”执行GET请求。此外,即使需要管理员授权,诸如“/users/test”等其他未来路由也将公开。为防止发生这种情况:如果路径变量的名称为“accountId”