Video in progress

Middle 🌱 Spring

Why does the order of requestMatchers rules matter in a Spring Security configuration? What's wrong with this configuration?

http.authorizeHttpRequests(auth -> auth
        .requestMatchers("/api/public/**").permitAll()
        .requestMatchers("/api/**").authenticated()
        .requestMatchers("/api/admin/**").hasRole("ADMIN")
        .anyRequest().denyAll());

The rules are checked top to bottom and the first match is applied. Here authenticated() for /api/** comes first, so the /api/admin/** rule below it never gets a turn, and any logged-in user can call the admin API.

📖 Answer

The rules in authorizeHttpRequests are stored as a list. When a request comes in, Spring Security compares them one after another and takes the first match. The path /api/admin/users matches /api/**, so authenticated() is enough.

The right order is from the more specific rule to the more general:

http.authorizeHttpRequests(auth -> auth
        .requestMatchers("/api/public/**").permitAll()
        .requestMatchers("/api/admin/**").hasRole("ADMIN")
        .requestMatchers("/api/**").authenticated()
        .anyRequest().denyAll());

This mistake is quiet: there's no exception, the application runs, and only the permission is wrong. So:

  • for every protected endpoint, write a test that says "a regular user gets 403" (@WithMockUser(roles = "USER"));
  • put anyRequest().denyAll() or authenticated() at the end, so a path forgotten in the list doesn't stay open;
  • hasRole("ADMIN") actually looks for the ROLE_ADMIN authority, so check how you store roles in the database.

On important paths, in addition to the URL rule, put @PreAuthorize on the service method as a second layer of protection.