0

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.

Rafi
  • 467
  • 6
  • 17
  • Unfortunately this does not solve my issue. I tried with multiple combinations like - ".antMatchers("/**").permitAll() .antMatchers("/internal/**").hasAnyRole("ROLE_A", "ROLE_B")" but didn't work – Rafi Oct 05 '22 at 18:23
  • 1
    The first rule that matches is applied. Because `.antMatchers("/**").permitAll()` is first, it is applied and subsequent rules are ignored. – Chin Huang Oct 05 '22 at 18:43
  • I tried with `.antMatchers("/internal/**").hasAnyRole("ROLE_A", "ROLE_B").antMatchers("/**").permitAll()`, I get 403 for both roles allowed and not allowed – Rafi Oct 05 '22 at 18:48

1 Answers1

0

Since I was using .hasAnyRole("ROLE_A", "ROLE_B") as opposed to .hasAnyAuthority("ROLE_A", "ROLE_B"), it was not working. I had to use .hasAnyRole("A", "B") to get it to work. The ROLE_ prefix gets added to the values automatically. So my working config is

http
    .csrf().disable()
    .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
    .authorizeRequests()
        .antMatchers("/internal/**").hasAnyRole("A", "B")
        .antMatchers("/**").permitAll()
dur
  • 15,689
  • 25
  • 79
  • 125
Rafi
  • 467
  • 6
  • 17