Authentication FlowΒΆ
Detailed authentication flow patterns and sequences for the five API authentication mechanisms β Basic Auth, Token Auth, JWT, OAuth, and Session Auth β as classified in Authentication Methods. Each section notes its honest status; check the Coverage Registry before treating a flow as runnable proof.
π Authentication ArchitectureΒΆ
sequenceDiagram
participant C as Client
participant F as Security Filter
participant P as Auth Provider
participant S as Security Context
participant A as API Controller
C->>F: HTTP Request with Credentials
F->>F: Extract Authentication Details
F->>P: Authenticate Request
P->>P: Validate Credentials
P-->>F: Authentication Result
F->>S: Set Security Context
F->>A: Forward Request
A->>A: Check Authorization
A-->>C: JSON Response π― Authentication Method FlowsΒΆ
1. HTTP Basic AuthenticationΒΆ
Status: Theory β not wired in this repository
No httpBasic(...) filter chain exists in the codebase today. The sequence below describes the standard BasicAuthenticationFilter mechanics for reference. The jdbc-only and ldap-only profiles authenticate via form login (Session Auth); their AuthenticationProviders could equally serve a Basic Auth chain if one is added.
sequenceDiagram
participant C as Client
participant F as Basic Auth Filter
participant P as DaoAuthenticationProvider
participant U as UserDetailsService
participant A as API Endpoint
C->>F: GET /api/jdbc/users<br/>Authorization: Basic dXNlcjpwYXNz
F->>F: Decode Base64 Credentials
F->>F: Extract Username & Password
F->>P: Authenticate(username, password)
P->>U: Load User Details
U->>U: Query Database/LDAP
U-->>P: UserDetails with Authorities
P->>P: Verify Password
P-->>F: Authentication Success
F->>F: Set Security Context
F->>A: Forward Request
A-->>C: Secured Response π Basic Auth Flow Learning Points:
- Request-Based: Credentials sent with every request
- Base64 Encoding: Username:password encoded (not encrypted)
- Database/LDAP Integration: User details loaded from data source
- Role Assignment: Authorities loaded with user details
π Basic Auth Header Format:
2. Token AuthenticationΒΆ
Two token styles are implemented and verified: opaque bearer tokens (introspection) and API keys.
sequenceDiagram
participant C as Client
participant F as Token Filter / Resource Server
participant I as Introspector / Key Store
participant A as API Endpoint
Note over C,A: Opaque bearer token (LAB-013)
C->>F: GET /op/...<br/>Authorization: Bearer <opaque-token>
F->>I: Introspect token (signature-free lookup)
I-->>F: active=true, scopes, subject
F->>A: Forward authenticated request
Note over C,A: API key (LAB-022 / LAB-026)
C->>F: GET /apikey/user<br/>X-API-Key: <key>
F->>I: Hash key, look up owner, check quota
I-->>F: Key owner + remaining quota
F->>A: Forward authenticated request π Token Auth Learning Points:
- Opaque tokens: nothing to verify locally β each request is resolved through
OpaqueTokenIntrospector, so revocation is immediate - API keys: a custom
OncePerRequestFilter(ApiKeyAuthenticationFilter) β the application owns hashing, rotation, scoping, and quotas - Where they run:
OpaqueTokenResourceServerConfigprotects/op/**; API-key chains are proven byApiKeysAndQuotasLabTestandApiKeyLifecycleLabTest - Status: Verified β Opaque Token Introspection, API Key Lifecycle
3. JWT Token AuthenticationΒΆ
Two JWT paths in this repository
The sequence below shows the educational custom JwtAuthenticationFilter (common-auth), which issues tokens at /api/auth/login and guards /api/** with a process-local symmetric key. The recommended production path is the standard resource server on /rs/** (oauth2ResourceServer().jwt()), proven by ResourceServerJwtLabTest in LAB-009.
sequenceDiagram
participant C as Client
participant L as Login Endpoint
participant J as JWT Util
participant F as JWT Filter
participant A as API Endpoint
Note over C,A: Step 1: Obtain JWT Token
C->>L: POST /api/auth/login<br/>username=admin&password=password
L->>J: Generate JWT Token
J->>J: Create Claims (username, role)
J->>J: Sign with Secret Key
J-->>L: JWT Token
L-->>C: {"token": "eyJhbGci..."}
Note over C,A: Step 2: Use JWT Token
C->>F: GET /api/admin/secure<br/>Authorization: Bearer eyJhbGci...
F->>F: Extract Token from Header
F->>J: Validate JWT Token
J->>J: Verify Signature & Expiry
J-->>F: Claims {username, role}
F->>F: Create Authentication Object
F->>A: Forward Request
A->>A: Check Role Authorization
A-->>C: Secured Response π JWT Flow Learning Points:
- Stateless Authentication: No server-side session storage
- Claims-Based: User identity and roles encoded in token
- Self-Contained: Token includes all necessary information
- Expiry Handling: Tokens have built-in expiration
π JWT Token Structure:
{
"header": {
"alg": "HS512",
"typ": "JWT"
},
"payload": {
"sub": "admin",
"role": "ROLE_ADMIN",
"iat": 1694520000,
"exp": 1694606400
},
"signature": "HMACSHA512(base64UrlEncode(header) + \".\" + base64UrlEncode(payload), secret)"
}
4. OAuth2 Authentication FlowΒΆ
sequenceDiagram
participant C as Client/Browser
participant A as Application
participant P as OAuth2 Provider
participant F as OAuth2 Filter
participant E as API Endpoint
Note over C,E: OAuth2 Authorization Code Flow
C->>A: Access Protected Resource
A-->>C: Redirect to OAuth2 Provider
C->>P: Login & Grant Permission
P-->>C: Redirect with Authorization Code
C->>A: Authorization Code
A->>P: Exchange Code for Access Token
P-->>A: Access Token & ID Token
A->>A: Create OAuth2User Principal
A->>A: Set Security Context
Note over C,E: Subsequent API Calls
C->>F: GET /api/oauth2/profile<br/>Cookie: JSESSIONID=...
F->>F: Load Authentication from Session
F->>E: Forward Request
E->>E: Extract OAuth2User Attributes
E-->>C: Profile Response with OAuth2 Data π OAuth2 Flow Learning Points:
- Authorization Code Flow: Most secure OAuth2 flow
- Session-Based: Post-authentication uses session cookies
- Attribute Mapping: Provider-specific user attributes
Status: partially verified
No external provider registrations (Google, GitHub, β¦) exist in this repository. The runnable path is the local IdP in infrastructure/idp/ (LAB-010, requires Docker) with OIDC SSO authority mapping verified by OidcAuthoritiesMapperTest in LAB-018. The oauth2-only profile chain exists but its oauth2Login(...) wiring is commented out.
5. Session-Based AuthenticationΒΆ
sequenceDiagram
participant C as Client
participant L as Login Form
participant P as Auth Provider
participant S as Session Manager
participant F as Session Filter
participant A as API Endpoint
Note over C,A: Initial Login
C->>L: POST /login (username, password)
L->>P: Authenticate Credentials
P-->>L: Authentication Success
L->>S: Create HTTP Session
S-->>C: Set-Cookie: JSESSIONID=ABC123
Note over C,A: Subsequent Requests
C->>F: GET /browser/profile<br/>Cookie: JSESSIONID=ABC123
F->>S: Retrieve Authentication from Session
S-->>F: Authentication Object
F->>A: Forward Request with Authentication
A-->>C: Secured Response π Session Flow Learning Points:
- Server-Side State: Authentication stored in server session
- Cookie-Based: Session ID transmitted via HTTP cookies
- CSRF Protection: Cross-Site Request Forgery mitigation
- Session Lifecycle: Login, timeout, logout management
Status: Verified on /browser/**
BrowserSecurityConfig wires this exact flow on /browser/** (SessionCreationPolicy.IF_REQUIRED, fixation protection, hardened cookies), proven by BrowserSessionLabTest in LAB-006. Note the endpoint above is /browser/profile, not /api/** β the /api/** chain is STATELESS and would ignore the session cookie.
π Authentication Method DetectionΒΆ
The API automatically detects and reports the authentication method used:
public String determineAuthType(Authentication auth) {
String principalType = auth.getPrincipal().getClass().getSimpleName();
if (principalType.contains("OAuth2")) {
return "OAuth2";
} else if (principalType.contains("Ldap")) {
return "LDAP";
} else if (principalType.contains("User")) {
return "JDBC/Database";
} else if (auth.getDetails().toString().contains("JWT")) {
return "JWT";
} else {
return "Custom/Session";
}
}
π‘οΈ Security Filter Chain OrderΒΆ
graph TD
A[HTTP Request] --> B[CSRF Filter]
B --> C[Logout Filter]
C --> D[OAuth2 Authorization Filter]
D --> E[OAuth2 Login Filter]
E --> F[JWT Authentication Filter]
F --> G[Basic Authentication Filter]
G --> H[Form Login Filter]
H --> I[Session Management Filter]
I --> J[Authorization Filter]
J --> K[Controller]
style A fill:#e1f5fe
style F fill:#c8e6c9
style G fill:#ececec,stroke-dasharray: 5 5
style J fill:#ffecb3
style K fill:#fff3e0 π Filter Chain Learning Points:
- Order Matters: Filters execute in specific sequence β the diagram shows Spring's standard ordering positions, not that every filter is active
- First Match Wins: First successful authentication is used
- Skip Logic: Authenticated requests skip unnecessary filters
- Exception Handling: Authentication failures handled gracefully
Which chains actually exist here
The Basic Authentication Filter is dashed because it is part of the standard order but not configured in this project. The wired chains are: stateless custom JWT filter on /api/**, the standard JWT resource server on /rs/**, opaque-token introspection on /op/**, and the stateful form-login chain on /browser/**.
π Authorization Decision FlowΒΆ
flowchart TD
A[Authenticated Request] --> B{URL Pattern Match}
B -->|/api/public/**| C[β
Allow - Public Access]
B -->|/api/admin/**| D{Has ROLE_ADMIN?}
B -->|/api/user/**| E{Has ROLE_USER or ROLE_ADMIN?}
B -->|Other patterns| F{Authenticated?}
D -->|Yes| G[β
Allow - Admin Access]
D -->|No| H[β 403 Access Denied]
E -->|Yes| I[β
Allow - User Access]
E -->|No| H
F -->|Yes| J[β
Allow - Authenticated Access]
F -->|No| K[β 401 Unauthorized]
style C fill:#c8e6c9
style G fill:#c8e6c9
style I fill:#c8e6c9
style J fill:#c8e6c9
style H fill:#ffcdd2
style K fill:#ffcdd2 π± Multi-Profile AuthenticationΒΆ
Different Spring profiles enable different authentication mechanisms. The profile names below match the @Profile annotations in MultiAuthSecurityConfig and the auth modules:
/api/** (educational JwtAuthenticationFilter) with the custom, JDBC, and LDAP providers registered. The /rs/** resource server and /browser/** session chains are active in every profile. AuthenticationProvider (SessionCreationPolicy.IF_REQUIRED). Not Basic Auth. AuthenticationProvider. π§ͺ Testing Authentication FlowsΒΆ
JWT Flow TestΒΆ
@Test
void jwtAuthenticationFlow() {
// Step 1: Get JWT token
ResponseEntity<Map> loginResponse = restTemplate.postForEntity(
"/api/auth/login",
createLoginRequest("admin", "password"),
Map.class
);
String token = (String) loginResponse.getBody().get("token");
// Step 2: Use JWT token
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(token);
ResponseEntity<Map> response = restTemplate.exchange(
"/api/admin/secure",
HttpMethod.GET,
new HttpEntity<>(headers),
Map.class
);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
Basic Auth Flow TestΒΆ
Illustrative only
This test would fail today β no httpBasic(...) chain is configured. Kept as the reference shape for when a Basic Auth lab is added.
@Test
void basicAuthenticationFlow() {
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth("jdbcadmin", "password");
ResponseEntity<Map> response = restTemplate.exchange(
"/api/jdbc/users",
HttpMethod.GET,
new HttpEntity<>(headers),
Map.class
);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
β‘ Performance ConsiderationsΒΆ
Authentication Method PerformanceΒΆ
| Method | Setup Cost | Request Cost | Scalability | Use Case |
|---|---|---|---|---|
| JWT | Low | Very Low | Excellent | Stateless APIs |
| Token Auth (opaque/API key) | Medium | Medium (lookup per request) | Good | Partner APIs, revocation-sensitive |
| Basic Auth | Low | Medium | Good | Simple internal APIs (Theory here) |
| OAuth2 | High | Low | Excellent | External identity |
| Session | Medium | Low | Fair | Traditional web apps |
Optimization TipsΒΆ
- JWT: Use short expiry times with refresh tokens
- Token Auth: Cache introspection results (LAB-024) and hash API keys (LAB-026)
- Basic Auth: Consider caching user details
- OAuth2: Implement token refresh logic
- Session: Configure appropriate session timeout
π Next StepsΒΆ
- Error Handling β - Authentication and authorization error patterns
- REST Endpoints β - Complete endpoint reference
- Security Configuration β - Deep dive into security setup
- Testing Examples β - Comprehensive testing patterns
π Understanding authentication flows is crucial for implementing secure APIs. Each method has specific use cases, benefits, and implementation patterns that suit different architectural requirements.