1

I have two paths:

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

I want to permit all for the first path and protect second path with role USER.

I tried below patterns but when I add first pattern, the second stop working (user can GET myPosts even if he doesn't have USER role). What I'm doing wrong?

.antMatchers(HttpMethod.GET, "/api/posts/{postId}").permitAll()
.antMatchers(HttpMethod.GET, "/api/posts/myPosts").hasRole("USER")
enyoucky
  • 103
  • 1
  • 9

2 Answers2

1

The problem is in the order of your rules. Reversing the order will work.

.antMatchers(HttpMethod.GET, "/api/posts/myPosts").hasRole("USER")
.antMatchers(HttpMethod.GET, "/api/posts/{postId}").permitAll()
Anant Goswami
  • 318
  • 3
  • 14
-1

The thing here is that you have to specify that all the paths are authenticated since it is not the default implementation of the HttpSecurity object.

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

I suggest to check this link here by the guys over at baeldung, they give a brief intro to Spring Security.