首页 > 解决方案 > 如何区分具有路径变量的 antMatchers 与上下文路径的其余部分

问题描述

我有两条路:

/api/posts/{postId}
/api/posts/myPosts

我想允许第一条路径的所有内容并使用角色 USER 保护第二条路径。

我尝试了以下模式,但是当我添加第一个模式时,第二个模式停止工作(即使他没有 USER 角色,用户也可以 GET myPosts )。我做错了什么?

.antMatchers(HttpMethod.GET, "/api/posts/{postId}").permitAll()
.antMatchers(HttpMethod.GET, "/api/posts/myPosts").hasRole("USER")

标签: springspring-security

解决方案


问题在于您的规则顺序。颠倒顺序将起作用。

.antMatchers(HttpMethod.GET, "/api/posts/myPosts").hasRole("USER")
.antMatchers(HttpMethod.GET, "/api/posts/{postId}").permitAll()

推荐阅读