I have two methods under the same Controller class - one is for a public endpoint and the other for the authorized users.
public class Controller {
@GetMapping("/endpoint")
public ResponseEntity public() {...}
@GetMapping("/internal/endpoint")
public ResponseEntity internal() {...}
}
And in the Security Configuration, I have:
http
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/**").permitAll()
.antMatchers("/internal/**").authenticated()
If I add @RolesAllowed({"ROLE_A", "ROLE_B"})
to the internal()
method I get a 403 for the roles that are not allowed. But If I remove that and add .antMatchers("/internal/**").hasAnyRole("ROLE_A", "ROLE_B")
to the security configuration it allows the users with unauthorized roles to access the internal endpoints.
My question is - can I use them interchangeably? If yes, what am I missing? Since I have quite a few internal endpoints I would prefer to have the role check in the security configuration rather that adding @RolesAllowed
to every internal method, but I am also open to follow the best practice.