antMatchers Spring Security模式,具有可更改的URL用户ID

我很长一段时间都在寻找答案但却找不到任何有效的方法

在我的rest服务中,我保留了一些function:/ account / {id} / download我想在SecurityConfig java文件中设置access ROLE,只有ROLE_TOKENSAVED用户可以访问这个url

当{id}可更改时,模式应该如何?

我尝试了一些正则表达式模式,但没有任何工作,我想要的,这是我的一些尝试:

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... } 

这对我有用:

 antMatchers("/account/{\\d+}/download").access("hasAnyAuthority('ROLE_TOKENSAVED')") 

注意表示ID的路径变量周围的花括号。

虽然Bohuslav建议的是有效的,但它并不完整。 根据AntPathMarcher的文档: http ://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/AntPathMatcher.html

您需要使用正则表达式指定路径变量:

{spring:[az]+} matches the regexp [az]+ as a path variable named "spring"

如果不这样做,您可能会暴露其他路线。 例如:

http .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 getAllRoles() { return userService.getAllRoles(); } 

因为您没有指定路径变量userId ,所以用户将能够在没有管理员权限的情况下对“/ users / roles”执行GET请求。 即使需要管理员授权,其他期货路线如“/ users / test”也会暴露出来。 为了防止:

antMatchers("/account/{accountId:[\\d+]}/download") .access("hasAnyAuthority('ROLE_TOKENSAVED')")

如果您的路径变量的名称是“accountId”