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

时间:2014-12-25 18:19:16

标签: java regex spring security spring-security

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

在我的休息服务中,我保留了一些功能:/ 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...
    }

2 个答案:

答案 0 :(得分:26)

这对我有用:

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

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

答案 1 :(得分:10)

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

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

{spring:[a-z]+} matches the regexp [a-z]+ 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<String> getAllRoles() {
    return userService.getAllRoles();
}

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

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

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