Spring Security Architecture
The security filter chain, OAuth2 resource servers with JWT, method security, multi-tenancy, service-to-service auth and common configuration mistakes.
How it works
Every HTTP request passes through the SecurityFilterChain: authentication filters (bearer token, session, form), exception translation, authorization filter. Authentication results live in the SecurityContext; authorization decisions use AuthorizationManagers.
flowchart LR REQ[HTTP request] --> F1[CORS / CSRF filters] F1 --> F2[BearerTokenAuthenticationFilter<br/>validate JWT via JWKS] F2 --> F3[AuthorizationFilter<br/>URL rules] F3 --> C[Controller] C --> M[Method security<br/>@PreAuthorize] M --> S[Service / domain checks<br/>object-level authorization]
OAuth2 resource server with JWT
@Configuration
@EnableMethodSecurity
class SecurityConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable()) // stateless API with bearer tokens
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/actuator/health/**").permitAll()
.requestMatchers(HttpMethod.GET, "/v1/orders/**").hasAuthority("SCOPE_orders.read")
.requestMatchers(HttpMethod.POST, "/v1/orders/**").hasAuthority("SCOPE_orders.write")
.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
.build();
}
}spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://login.example.com/realms/acme # discovers JWKS, validates iss
audiences: orders-api # validate audObject-level authorization (prevent BOLA)
@Service
class OrderQueries {
@PreAuthorize("hasAuthority('SCOPE_orders.read')")
@PostAuthorize("returnObject.customerId() == authentication.name or hasRole('SUPPORT')")
public OrderView get(String orderId) { return repository.view(orderId); }
}For lists, filter in the query (WHERE customer_id = :currentUser) rather than after loading.
Service-to-service
- OAuth2 client credentials (
spring-boot-starter-oauth2-client) with token caching for calls to other APIs. - Or mTLS via service mesh plus workload identity.
- Token exchange (RFC 8693) when propagating user context to downstream services with narrowed scopes.
Common mistakes
- Not validating
aud(accepting tokens meant for another API). - Authorization only at the gateway, not in the service.
- Disabling CSRF for browser apps that use cookies.
- Long-lived JWTs with no revocation strategy.
- Logging tokens.
Interview questions and answers
Session cookies or JWT for a browser SPA?
For browser apps, the recommended pattern is a backend-for-frontend that keeps tokens server-side and gives the browser an HttpOnly, Secure, SameSite session cookie (OAuth 2.0 for Browser-Based Apps guidance). JWT bearer tokens fit service APIs and mobile clients.
How do you revoke a JWT?
Keep access tokens short-lived (minutes), revoke refresh tokens at the authorization server, and for high-risk cases check a denylist or use opaque tokens with introspection.