Sub topic 3
Protecting Endpoints with Spring Security
This chapter assumes basic Spring Boot MVC, HTTP status codes, authentication versus authorization, and Java 17 with Maven or Gradle. The application is already configured as a JWT resource server.
Request Rules and Method Security
Use request rules for broad URL protection. Public endpoints can be open, while other endpoints require authentication or a specific authority.
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
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();
}
}For a finer check, use @PreAuthorize on a controller or service method:
@PreAuthorize("hasAuthority('SCOPE_orders.read')")
@GetMapping("/orders")
List<String> orders() {
return List.of("order-1", "order-2");
}Request rules answer “which URLs are protected?” Method security answers “which operation may this caller perform?”
401, 403, and Tests
A 401 Unauthorized response means the request has no usable authentication. The caller must provide a valid bearer token. A 403 Forbidden response means authentication succeeded, but the token lacks the required authority.
MockMvc can test these outcomes without contacting a real authorization server:
@Test
void ordersRequireScope() throws Exception {
mockMvc.perform(get("/orders")
.with(jwt().authorities(
new SimpleGrantedAuthority("SCOPE_orders.read"))))
.andExpect(status().isOk());
mockMvc.perform(get("/orders").with(jwt()))
.andExpect(status().isForbidden());
mockMvc.perform(get("/orders"))
.andExpect(status().isUnauthorized());
}Import jwt from SecurityMockMvcRequestPostProcessors and include spring-security-test.
Alternatives and Operational Risks
Opaque tokens contain no readable claims. The resource server sends each token to an introspection endpoint, which returns whether it is active and which claims it has. Introspection supports near-immediate revocation but adds network latency and creates a dependency on the authorization server. JWT validation is usually faster because the API verifies the token locally.
With JWTs, providers publish signing keys through a JWKS endpoint. Spring Security caches those keys and refreshes them when a new key appears, allowing key rotation without redeploying the API.
Short token lifetimes reduce the impact of stolen tokens. JWTs are otherwise difficult to revoke before expiry. Configure CORS deliberately for browser clients, and never place bearer tokens in URLs or insecure browser storage.
Exercise
A caller sends a valid JWT but lacks the admin authority. Which status should an /admin/** rule return?
Show answer
403 Forbidden, because the caller is authenticated but not authorized.