'Why can I access Admin APIs with user credentials in basic auth Spring?

On hitting Admin Api GET http://localhost:8080/v1/admin/hello Spring Security is asking for credentials but by providing user credential (Username: user and password: user) api is returning with 200 Status. I believe it should return 401 UnAuthorised for Admin Apis as i have passed user credentials instead of Admin creds.

What am I missing?

Following is my Controller class

@RestController
@RequestMapping("/v1")
public class HelloController {
    
    @GetMapping("/admin/hello")
    public String print123() {
        return "Hello admin";
    }
    
    @GetMapping("/user/hello")
    public String printAbc() {
        return "Hello user";
    } 
}

Following is spring securityConfig

@Configuration
@EnableWebSecurity
public class AuthConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  private BasicAuthenticationPoint basicAuthenticationPoint;


  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
    http.authorizeRequests().antMatchers("/user/**").hasRole("USER")
                            .antMatchers("/admin/**").hasRole("ADMIN")
                            .anyRequest().authenticated();
    http.httpBasic().authenticationEntryPoint(basicAuthenticationPoint);

  }
  
  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.inMemoryAuthentication()
              .withUser("user").password("{noop}user").roles("USER")
              .and()
              .withUser("admin").password("{noop}admin").roles("ADMIN", "USER");
  }
  
}


Solution 1:[1]

The matchers in AuthConfig are for "/user/**" and "/admin/**".

A request to http://localhost:8080/v1/admin/hello doesn't match either of those, so it is falls into the .anyRequest().authenticated() access rule.

Perhaps you meant to say .antMatchers("/v1/admin/**").hasRole("ADMIN").

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eleftheria Stein-Kousathana