antMatchers Spring Security pattern with changeable URL user ID
Though what Bohuslav suggest works, it is not complete. According to the documentation for AntPathMarcher: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/AntPathMatcher.html
You need to specify the path variable with the regex:
{spring:[a-z]+} matches the regexp [a-z]+ as a path variable named "spring"
If you don't, you may expose other routes. For example:
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/users/{^[\\d]$}").authenticated()
.antMatchers("/users/**").hasAuthority("admin")
and these methods on a 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();
}
Because you didn't specify path variable, userId
, users will be able to do a GET request on "/users/roles" without having the admin authority. Also other futures routes like "/users/test" will also be exposed even if admin authorization is required. To prevent that:
antMatchers("/account/{accountId:\\d+}/download")
.access("hasAnyAuthority('ROLE_TOKENSAVED')")
if your path variable's name was "accountId"
This works for me:
antMatchers("/account/{\\d+}/download").access("hasAnyAuthority('ROLE_TOKENSAVED')")
Notice the curly braces around the path variable representing the ID.