Spring 如何区分带有path变量的AntMatcher与上下文路径的其余部分

Spring 如何区分带有path变量的AntMatcher与上下文路径的其余部分,spring,spring-security,Spring,Spring Security,我有两条路: /api/posts/{postId} /api/posts/myPosts 我想允许第一条路径的所有操作,并使用角色用户保护第二条路径 我尝试了以下模式,但当我添加第一个模式时,第二个模式停止工作(用户可以获得我的帖子,即使他没有用户角色)。 我做错了什么 .antMatchers(HttpMethod.GET, "/api/posts/{postId}").permitAll() .antMatchers(HttpMethod.GET, "/api/posts/myPosts

我有两条路:

/api/posts/{postId}
/api/posts/myPosts
我想允许第一条路径的所有操作,并使用角色用户保护第二条路径

我尝试了以下模式,但当我添加第一个模式时,第二个模式停止工作(用户可以获得我的帖子,即使他没有用户角色)。 我做错了什么

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

问题在于你的规则的顺序。颠倒顺序就行了

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

问题在于你的规则的顺序。颠倒顺序就行了

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

这里的问题是,您必须指定所有路径都经过身份验证,因为它不是HttpSecurity对象的默认实现

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

我建议baeldung的同事们在这里检查一下,他们会简单介绍一下Spring Security

这里的问题是,您必须指定所有路径都经过身份验证,因为它不是HttpSecurity对象的默认实现

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

我建议baeldung的同事们在这里检查一下,他们会简单介绍一下Spring Security

换线。命令很重要,换线。秩序很重要,你的答案是错的。你试过了吗?我已经有了这一行:.anyRequest().authenticated()@阿南戈斯瓦米的答案是好的,你的答案是错的。你试过了吗?我已经有了这一行:.anyRequest().authenticated()@阿南特戈斯瓦米的回答很好。