Authorization code with PKCE through the BFF
| This documentation was generated with the assistance of AI. Please report any inaccuracies. |
The browser never takes part in the OAuth exchange as a client. The single page application (SPA) served by the bff
asks the BFF to sign the user in; the BFF runs the authorization code flow with PKCE against auth-server as the
confidential client bff, exchanges the code with its client secret, and keeps the access, refresh and ID tokens in
its server-side session, stored in PostgreSQL by Spring Session JDBC. The browser only holds the __Host-SESSION
cookie. When the SPA asks for the user’s documents, the BFF calls the resource server with the access token of the
session and answers with its own response.
At a glance
| Item | Value |
|---|---|
Actors |
User and browser (the SPA from |
Client |
|
Preconditions |
|
BFF endpoints |
|
Authorization server endpoints |
|
Resource server endpoint |
|
Steps
-
The SPA calls
GET /bff/user. Without a session the BFF chain answers401(requests under/bff/and/api/get anHttpStatusEntryPoint, not a redirect), and the SPA shows its Sign in button. -
The user clicks it and the browser navigates to
GET /bff/login?returnTo=/.BffLoginControllerchecksreturnToagainstbff.login.allowed-return-paths, stores it in the session and answers302to/oauth2/authorization/bff. -
Spring Security’s authorization request filter builds the request with the
DefaultOAuth2AuthorizationRequestResolverthatSecurityConfig.bffFilterChaincustomises withOAuth2AuthorizationRequestCustomizers.withPkce()(Spring only adds PKCE by itself for public clients). It keepsstate,nonceand thecode_verifierin the BFF session and redirects the browser toauth-server/oauth2/authorizewithcode_challengeandcode_challenge_method=S256. -
The protocol chain (
SecurityConfig.authorizationServerSecurityFilterChain) sees no session and sends the browser to/loginthrough itsLoginUrlAuthenticationEntryPoint. The user signs in with any method the login page offers (see Authentication methods inside the authorization code flow). -
If the MFA policy is not satisfied (
MfaProtocolChainCustomizer,MfaAuthorizationManager), the browser is sent to/login/second-factor; once the factor is proved, the saved authorization request resumes. -
bffrequires consent, so Spring Authorization Server redirects to the custom consent page (ConsentProtocolCustomizer,ConsentController,templates/consent.html) unless the user already granted every requested scope. Allow posts the approved scopes to/oauth2/authorize; Deny posts none and the BFF getserror=access_denied. -
auth-serverredirects tohttp://localhost:8080/login/oauth2/code/bff?code=…&state=…;. -
The BFF’s login filter checks
stateand posts the code, theredirect_uriand thecode_verifierto/oauth2/token, authenticating withclient_secret_basic. The server checks the code verifier against the stored challenge and answers with an access token, a refresh token and an ID token. -
The BFF validates the ID token with the keys from
/oauth2/jwks(found through the issuer’s discovery document), builds anOidcUserand stores the authorized client in the session throughHttpSessionOAuth2AuthorizedClientRepository. Spring Session JDBC writes the session to thespring_sessiontables of thebffdatabase (V300__spring_session.sql). -
ReturnToAuthenticationSuccessHandlerreads and removes the storedreturnTo, validates it again and redirects there. The SPA callsGET /bff/useragain, andUserControlleranswers with the claims of theOidcUser. -
The SPA calls
GET /api/documents.DocumentsControllercallsListDocumentsUseCase, whose portDocumentGatewayis implemented byRestDocumentGateway. The generated client runs on aRestClientwithOAuth2ClientHttpRequestInterceptor, which asks theOAuth2AuthorizedClientManagerfor the session’s access token (renewing it with the refresh token when it expired, see Refresh token rotation and reuse detection) and sends it asAuthorization: Bearerto the resource server. -
The resource server validates the JWT (issuer, signature, audience
resource-server, scopedocuments.read) and answers.RestDocumentGatewaymaps the answer, or translates a failure into a domain exception, and the BFF answers the SPA with its own body: no token, header or error body of the resource server reaches the browser. -
Deleting (
DELETE /api/documents/{id}, with the CSRF token) goes the same way with thedocuments.deletescope, but the resource server also requires a recent multi-factor sign-in. Without one it answers the RFC 9470 challenge, which the BFF turns into a401problemurn:problem:documents:step-up-requiredwithacrValuesandmaxAge(the only values of the resource server that reach the browser). The SPA signs in again throughGET /bff/login?returnTo=…&acrValues=…&maxAge=…, which addsacr_valuesandmax_ageto the next authorization request, and retries; see Step-up authentication.
The branches of the authorization request on auth-server:
The session store and the authorized client manager of the BFF:
/**
* Keeps the authorized clients (the tokens of the signed-in user) in the HTTP session, which Spring Session JDBC
* persists, so no table of its own is needed and the tokens never reach the browser.
*
* @return the repository of authorized clients.
*/
@Bean
OAuth2AuthorizedClientRepository authorizedClientRepository() {
return new HttpSessionOAuth2AuthorizedClientRepository();
}
/**
* Builds the manager that obtains the access token of the signed-in user and renews it with its refresh token when
* it expires.
*
* @param clientRepository the registered OAuth2 clients.
* @param authorizedClientRepository where the authorized clients are kept.
* @return the authorized client manager, with the {@code authorization_code} and {@code refresh_token} providers.
*/
@Bean
OAuth2AuthorizedClientManager authorizedClientManager(final ClientRegistrationRepository clientRepository,
final OAuth2AuthorizedClientRepository authorizedClientRepository) {
final var manager = new DefaultOAuth2AuthorizedClientManager(clientRepository, authorizedClientRepository);
manager.setAuthorizedClientProvider(OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken()
.build());
return manager;
}
Tokens and claims
The token response goes to the BFF only:
-
Access token: a JWT signed with the active key (
RS256),subthe username,audresource-serverandauth-server(the client’saudiences),scope,roles,tenant, andamr,acrandauth_timefromMfaClaimsContributor. Lifetime 10 minutes. -
Refresh token: opaque, 8 hours, replaced on every use.
-
ID token:
sub,audbff,azp,nonce,amrandacr; noroles,tenantor customaud. See OpenID Connect sign-in.
The SPA sees none of them. GET /bff/user answers a SessionUserResponse built from the OidcUser by
SessionUserDtoMapper.
How it is tested
-
e2e-testsBffEndToEndIT: the packagedauth-server,resource-serverandbffin headless Chromium. Signs in through the login and consent pages, lists the documents, signs out, and scans every response, the storages and the cookies for tokens; a second scenario denies consent and checks that no session is created. -
e2e-testsSignInSmokeIT: the demo user signs in through the BFF and/bff/usercarries the subject. -
bff/bootSecurityConfigIT: the authorization request carries PKCE (bffFilterChain_whenAuthorizationIsRequested_usesPkce), a failed sign-in lands on/?error=signin,returnTois validated. -
bff/bootBffSessionIT: the session is stored in PostgreSQL with the hardened__Host-cookie. -
bff/bootDocumentsApiIT: the bearer token is sent upstream and kept from the browser; resource server failures are mapped to401,403,404and502, a step-up challenge to thestep-up-requiredproblem, and a client that only accepts JSON is not refused with406. -
bff/bootSecurityConfigITalso checks that both document scopes are requested and that a login started withacrValues/maxAgesends them once asacr_values/max_age. -
e2e-testsBffEndToEndIT(third scenario): a password-only session’s deletion answers the step-up problem and the step-up login reaches the authorization server’s second-factor page. -
bff/bootUserControllerIT:GET /bff/usersigned in and anonymous. -
auth-server/bootAuthorizationCodePkceITandConsentPageIT: the server side of the code flow and the consent page.