Java 具有可变 URL 用户 ID 的 antMatchers Spring Security 模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27649649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:47:21  来源:igfitidea点击:

antMatchers Spring Security pattern with changeable URL user ID

javaregexspringsecurityspring-security

提问by azalut

I was looking for the answer for a long time but couldnt find anything productive

我一直在寻找答案,但找不到任何富有成效的东西

In my rest service I keep some functionality under: /account/{id}/download and I would like to set the acces ROLE in SecurityConfig java file, that only ROLE_TOKENSAVED users can access this url

在我的休息服务中,我将一些功能保留在:/account/{id}/download 下,我想在 SecurityConfig java 文件中设置访问角色,只有 ROLE_TOKENSAVED 用户可以访问此 url

How should the pattern look like, when {id} is changeable?

当 {id} 可变时,模式应该是什么样子的?

I tried some regexp patterns, but nothing worked as I wanted, here are some of my attempts:

我尝试了一些正则表达式模式,但没有任何效果,以下是我的一些尝试:

1. antMatchers("account/**/download").access(somerolehere)
2. antMatchers("account/\d/download").access(somerolehere)
3. antMatchers("account/[\d]/download").access(somerolehere)

thanks in advance for your anserwers :)

提前感谢您的回答:)

edit:

编辑:

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

采纳答案by Bohuslav Burghardt

This works for me:

这对我有用:

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

Notice the curly braces around the path variable representing the ID.

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

回答by LethalLima

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

尽管 Bohuslav 的建议有效,但并不完整。根据 AntPathMatcher 的文档: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"

{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:

以及 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:

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

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

if your path variable's name was "accountId"

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