Sub topic 10
Protecting endpoints with request rules
This chapter assumes you have a Spring Boot app configured as a JWT resource server, with issuer-uri set and a working JwtDecoder. It also assumes you know how scopes become SCOPE_ authorities. Here you decide which URLs need which authorities.
How request rules work
Request rules live in a SecurityFilterChain bean. You declare them with authorizeHttpRequests. Spring Security checks the rules in the order you write them. The first matcher that fits the request decides the outcome, and later rules are never consulted.
A complete filter chain
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasAuthority("SCOPE_admin")
.anyRequest().authenticated())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}
}The chain does three things:
/public/**is open to everyone./admin/**needs theSCOPE_adminauthority, which comes from the token'sscopeclaim.anyRequest().authenticated()is a catch-all. It means that a URL you forgot to list still requires a valid token.
STATELESS tells Spring not to create an HttpSession. Each request must carry its own bearer token.
Rules to follow
- Order from specific to general. If
anyRequest()came first, the/admin/**rule would never run. Spring rejects a rule added afteranyRequest(), so that mistake fails at startup. - End with a catch-all. Use
authenticated()ordenyAll(). A chain with no catch-all leaves unmatched URLs under whatever default applies. - Match the prefix to your authorities. The default converter produces
SCOPE_admin, notadmin. The rulehasAuthority("admin")will always deny.hasRole("ADMIN")looks forROLE_ADMIN, so it only works if you mapped roles with that prefix. - Restrict by method when needed.
requestMatchers(HttpMethod.POST, "/orders/**")applies a rule to POST only, so reads and writes can need different scopes.
Common surprises
permitAll()does not skip token checks. If a client sends an expired or malformed bearer token to/public/**, the resource server filter rejects it with 401 before your rule runs.permitAll()only means that no authentication is required.- 401 versus 403. A missing or invalid token produces 401. A valid token without the needed authority produces 403. Check the token first when debugging a 403, because the scope may simply be absent from the
scopeclaim. - Path patterns.
/admin/**matches/adminand everything below it. A pattern like/admin/*covers only one level.
Exercise
A chain lists .anyRequest().authenticated() first, then .requestMatchers("/admin/**").hasAuthority("SCOPE_admin"). What happens, and how do you fix it?
Show answer
Spring Security rejects the configuration at startup, because no rule may follow anyRequest(). If it were allowed, the first rule would match every request, so the admin rule would never apply. Put the specific /admin/** matcher first and keep anyRequest() last.