Login pages and the BFF

This documentation was generated with the assistance of AI. Please report any inaccuracies.

This page describes the server-rendered pages of auth-server (login, consent, logout) and how the bff signs users in for a single page application (SPA) without ever exposing a token to the browser.

Login page

The pages are Thymeleaf templates under auth-server/api/web/src/main/resources/templates. They share one layout (fragments/layout.html) that renders the branding header and footer, and load a stylesheet from the same origin: there is no inline script or style, which is what lets the content security policy be strict. The text comes from messages.properties (English; spring.web.locale: en and no fallback to the system locale, so the language never depends on the machine).

<html xmlns:th="http://www.thymeleaf.org" th:fragment="layout(title, content)" th:lang="${#locale.language}" lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title th:replace="${title}">Authorization server</title>
  <link rel="stylesheet" th:href="@{/css/pages.css}">
</head>
<body>
<header class="branding">
  <img th:if="${branding != null and !#strings.isEmpty(branding.logoUrl)}" th:src="${branding.logoUrl}" alt=""
       class="branding-logo">
  <span class="branding-name" th:text="${branding != null} ? ${branding.applicationName} : 'Irurueta Auth Server'">
    Irurueta Auth Server</span>
</header>
<main th:replace="${content}">
  <p>Page content</p>
</main>
<footer th:if="${branding != null and !#strings.isEmpty(branding.footerText)}" th:text="${branding.footerText}"></footer>
</body>
</html>

Each page is an operation of the contract apis/auth-server/web-pages/auth-server-pages-v1.yaml, like every other endpoint of the application: openapi-generator turns it into an interface (LoginPageApi, ConsentPageApi, LogoutPageApi) whose method answers the page as text/html, and the controller only implements it. No controller carries a mapping annotation of its own (HexagonalArchitectureTest fails the build otherwise), and OpenApiDriftIT compares the contract with the springdoc group pages (/v3/api-docs/pages). The login page is public; the consent and logout pages need the session.

  /login:
    get:
      tags: [ Login page ]
      operationId: loginPage
      summary: Renders the sign-in page
      description: >-
        Renders the sign-in page with the form of every sign-in method (each LoginMethodFragment bean contributes
        one). The forms post to the security chain (POST /login), never to this operation. Public: it is where the
        browser is sent when it has no session.
      security: [ ]
      parameters:
        - name: error
          in: query
          required: false
          description: >-
            Present (its value is ignored, usually empty) when the previous sign-in failed; the page then shows the
            message of that failure, which never reveals whether the account exists.
          schema:
            type: string
        - name: logout
          in: query
          required: false
          description: >-
            Present (its value is ignored, usually empty) when the user has just signed out; the page then says so.
          schema:
            type: string
      responses:
        '200':
          description: The sign-in page.
          content:
            text/html:
              schema:
                type: string

A controller builds the model and hands the template to PageRenderer, which resolves the view through the application’s view resolvers, with the locale of the request, and renders it against the current request into a response wrapper that captures the markup. Rendering against the real request is what keeps the templates working: th:action still adds the CSRF hidden field, @{…​} links and #{…​} messages resolve as before. The markup is then answered as the text/html body of the generated method.

    /**
     * Renders the login page.
     *
     * @param error  present (even if empty) when the previous attempt failed.
     * @param logout present (even if empty) when the user has just signed out.
     * @return the login page.
     */
    @Override
    public ResponseEntity<String> loginPage(final String error, final String logout) {
        final var model = new HashMap<String, Object>();
        model.put(LOGIN_PATH_ATTRIBUTE, LOGIN_PATH);
        model.put(FRAGMENTS_ATTRIBUTE, fragments);
        if (error != null) {
            model.put(ERROR_MESSAGE_ATTRIBUTE, errorMessages.keyOf(lastFailure()));
        }
        model.put(LOGGED_OUT_ATTRIBUTE, logout != null);
        return pageRenderer.render(VIEW_NAME, model);
    }

The login page itself contains no sign-in method. Each LoginMethodFragment bean contributes one, rendered below the heading, so adding a method never edits the page. The username and password form is the fragment of PasswordLoginFragment, in password.html.

<html xmlns:th="http://www.thymeleaf.org" th:replace="~{fragments/layout :: layout(~{::title}, ~{::main})}">
<head>
  <title th:text="#{login.title}">Sign in</title>
</head>
<body>
<main>
  <h1 th:text="#{login.heading}">Sign in</h1>
  <div th:if="${errorMessageKey != null}" role="alert" th:text="#{${errorMessageKey}}">Invalid username or password.</div>
  <div th:if="${loggedOut}" role="status" th:text="#{login.logout}">You have been signed out.</div>
  <section th:each="fragment : ${fragments}" class="login-method">
    <!-- LoginMethodFragment.reference() is the single source of the "template :: fragment" expression -->
    <div th:replace="~{__${fragment.reference()}__}"></div>
  </section>
</main>
</body>
</html>
<form th:fragment="form" method="post" th:action="@{${loginPath}}">
  <p>
    <label for="username" th:text="#{login.username}">Username</label>
    <input type="text" id="username" name="username" required autofocus autocomplete="username">
  </p>
  <p>
    <label for="password" th:text="#{login.password}">Password</label>
    <input type="password" id="password" name="password" required autocomplete="current-password">
  </p>
  <button type="submit" th:text="#{login.submit}">Sign in</button>
</form>

Branding is configured under authserver.ui.branding.* (application name, logo URL, footer text), with defaults, and added to the model of every page by PageRenderer (and of the error page by ErrorPageViewResolver), both through BrandingProvider. The logo is either a path served by this application or an absolute http(s) URL on another origin, which the content security policy then allows for images (see below); a protocol-relative URL (//host/…​) is not recognised as another origin, so write the scheme.

/**
 * Branding shown by the login, consent, logout and error pages, bound from {@code authserver.ui.branding.*}.
 *
 * @param applicationName name shown in the page header and title; defaults to {@link #DEFAULT_APPLICATION_NAME}.
 * @param logoUrl         optional URL of a logo image: a path served by this application, or an absolute
 *                        {@code http(s)} URL whose origin the content security policy then allows for images; empty
 *                        when there is none.
 * @param footerText      optional text shown below every page; empty when there is none.
 */
@ConfigurationProperties("authserver.ui.branding")
public record BrandingProperties(String applicationName, String logoUrl, String footerText) {

    /** Application name used when none is configured. */
    public static final String DEFAULT_APPLICATION_NAME = "Irurueta Auth Server";

    /**
     * Applies the defaults.
     *
     * @param applicationName name shown in the page header, blank for the default.
     * @param logoUrl         optional logo URL, blank for none.
     * @param footerText      optional footer text, blank for none.
     */
    public BrandingProperties {
        applicationName = StringUtils.hasText(applicationName) ? applicationName : DEFAULT_APPLICATION_NAME;
        logoUrl = StringUtils.hasText(logoUrl) ? logoUrl : "";
        footerText = StringUtils.hasText(footerText) ? footerText : "";
    }
}

Security headers

LoginHeadersCustomizer adds a Content-Security-Policy, X-Content-Type-Options: nosniff and Referrer-Policy: no-referrer to the pages of the login chain. The policy is built by LoginContentSecurityPolicy from the branding: default-src 'self'; frame-ancestors 'none'; img-src 'self' data: (same-origin resources only, no framing, and data: images for the QR code of an authenticator app, rendered in memory so its secret never becomes a resource of its own) and, when the logo is an absolute http(s) URL, the origin of the logo is added to img-src, so the logo loads while scripts, styles and every other resource stay same-origin.

The policy has deliberately no form-action directive. Browsers also apply it to the redirects that follow a form submission, so form-action 'self' blocked (in Chromium) the redirect from the login or consent form back to the client application’s redirect_uri, which is on another origin.

/**
 * Adds the security headers of the server-rendered pages: the content security policy that
 * {@link LoginContentSecurityPolicy} builds (same-origin resources only, no framing, and the origin of an absolute
 * branding logo URL for images), {@code X-Content-Type-Options} and {@code Referrer-Policy}.
 *
 * <p>The policy deliberately has no {@code form-action} directive: browsers also apply it to the redirects that follow
 * a form submission, so {@code form-action 'self'} would block the redirect from the login or consent form back to the
 * client application's {@code redirect_uri}, which is on another origin.
 */
@Component
@Order(0)
@RequiredArgsConstructor
public class LoginHeadersCustomizer implements LoginChainCustomizer {

    /** Builds the content security policy from the branding. */
    private final LoginContentSecurityPolicy contentSecurityPolicy;

    @Override
    public void customize(final HttpSecurity http) {
        final var policy = contentSecurityPolicy.policy();
        http.headers(headers -> {
            headers.contentSecurityPolicy(csp -> csp.policyDirectives(policy));
            headers.contentTypeOptions(Customizer.withDefaults());
            headers.referrerPolicy(referrer -> referrer.policy(ReferrerPolicy.NO_REFERRER));
        });
    }
}
/**
 * Builds the content security policy of the server-rendered pages from the {@link BrandingProperties}: same-origin
 * resources only and no framing, except that images may also be {@code data:} URIs (the QR code of an authenticator
 * app, rendered in memory so its secret never becomes a resource of its own) and, when the branding logo is an
 * absolute {@code http(s)} URL, come from its origin ({@code img-src 'self' data: <scheme://host[:port]>}). A relative
 * logo URL is same-origin and needs nothing more.
 */
@Component
@RequiredArgsConstructor
public class LoginContentSecurityPolicy {

    /**
     * Policy of the pages when the logo, if any, is served by this application. Its last directive lists the image
     * sources, so the origin of an absolute logo URL is appended to it.
     */
    public static final String DEFAULT_POLICY = "default-src 'self'; frame-ancestors 'none'; img-src 'self' data:";

    /** Schemes whose origin is added for an absolute logo URL. */
    private static final Set<String> WEB_SCHEMES = Set.of("http", "https");

    /** Provider of the configured branding; absent in web slices that do not enable the properties. */
    private final ObjectProvider<BrandingProperties> branding;

    /**
     * Builds the policy.
     *
     * @return {@link #DEFAULT_POLICY}, with the logo's origin added to its {@code img-src} directive when the logo is
     *         an absolute {@code http(s)} URL.
     */
    public String policy() {
        final var logoUrl = branding.getIfAvailable(() -> new BrandingProperties(null, null, null)).logoUrl();
        return originOf(logoUrl).map(origin -> DEFAULT_POLICY + " " + origin).orElse(DEFAULT_POLICY);
    }

    /**
     * Extracts the origin of an absolute {@code http(s)} URL.
     *
     * @param url the URL; may be empty.
     * @return {@code scheme://host[:port]} in lower case, or empty when the URL is relative, not {@code http(s)},
     *         has no host or cannot be parsed.
     */
    private static Optional<String> originOf(final String url) {
        try {
            final var uri = new URI(url);
            final var scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT);
            if (!WEB_SCHEMES.contains(scheme) || uri.getHost() == null) {
                return Optional.empty();
            }
            final var port = uri.getPort() < 0 ? "" : ":" + uri.getPort();
            return Optional.of(scheme + "://" + uri.getHost().toLowerCase(Locale.ROOT) + port);
        } catch (final URISyntaxException invalid) {
            return Optional.empty();
        }
    }
}

Sign-in errors and user enumeration

A failed sign-in shows one message. A wrong password and an unknown user share the generic "Invalid username or password.", so the page never tells whether an account exists. The account status messages (locked, disabled, expired account, expired password) could tell it, because Spring Security’s default DaoAuthenticationProvider checks the status before the password: a wrong password for a disabled account would answer "This account is disabled.". The password feature therefore declares its own provider (PasswordAuthenticationConfiguration) that checks nothing before the password and the status after it (AccountStatusUserDetailsChecker): a wrong password always gets the generic message, and a status message only appears to someone who typed the correct password. Everything else is as the provider Spring Security would build: the password encoder, the hash upgrade on sign-in through UserAccountUserDetailsService, a CompromisedPasswordChecker when one bean of that type exists, and unknown users hidden behind bad credentials.

    /**
     * Creates the authentication provider of the username and password sign-in.
     *
     * @param userDetailsService         loads the account by username.
     * @param userDetailsPasswordService stores the upgraded hash after a sign-in with an outdated encoding.
     * @param passwordEncoder            verifies the password, and tells when its hash needs upgrading.
     * @param compromisedPasswordChecker the compromised-password checker of Spring Security, when one is declared.
     * @return the provider, which checks the account status only after a correct password.
     */
    @Bean
    public DaoAuthenticationProvider passwordAuthenticationProvider(final UserDetailsService userDetailsService,
            final UserDetailsPasswordService userDetailsPasswordService, final PasswordEncoder passwordEncoder,
            final ObjectProvider<CompromisedPasswordChecker> compromisedPasswordChecker) {
        final var provider = new DaoAuthenticationProvider(userDetailsService);
        provider.setPasswordEncoder(passwordEncoder);
        provider.setUserDetailsPasswordService(userDetailsPasswordService);
        compromisedPasswordChecker.ifUnique(provider::setCompromisedPasswordChecker);
        provider.setHideUserNotFoundExceptions(true);
        provider.setPreAuthenticationChecks(NO_PRE_AUTHENTICATION_CHECKS);
        provider.setPostAuthenticationChecks(new AccountStatusUserDetailsChecker());
        return provider;
    }
The account model only has an enabled flag, so UserDetailsMapper only produces disabled accounts; the locked, expired-account and expired-password messages exist in LoginErrorMessages and messages.properties but are not produced yet.

The authorization endpoint is pointed at the custom consent page (ConsentProtocolCustomizer) instead of the generated one. The page lists the requested scopes with a description each, as checkboxes that are checked by default, and the scopes already granted. Allow posts the approved scopes back to /oauth2/authorize; Deny posts none, which the authorization endpoint answers with error=access_denied, and the BFF then shows a sign-in failure.

Consent is a property of the registered client: requireConsent in the client registration and in the clients API (POST and PUT /api/admin/clients; default false). The default bff client requires it, spa-public does not.

<html xmlns:th="http://www.thymeleaf.org" th:replace="~{fragments/layout :: layout(~{::title}, ~{::main})}">
<head>
  <title th:text="#{consent.title}">Authorize application</title>
</head>
<body>
<main>
  <h1 th:text="#{consent.heading(${consent.clientName})}">Authorize application</h1>
  <p th:text="#{consent.intro(${consent.clientName}, ${consent.principalName})}">The application wants access.</p>
  <!-- the decision is posted back to the authorization endpoint, which reads client_id, state and the approved scopes, or
       to the device verification endpoint, which also reads the user code, when the consent is asked for a device -->
  <form method="post" th:action="@{${decisionPath}}">
    <input type="hidden" name="client_id" th:value="${consent.clientId}">
    <input type="hidden" name="state" th:value="${consent.state}">
    <input type="hidden" name="user_code" th:if="${userCode}" th:value="${userCode}">
    <p th:if="${#lists.isEmpty(consent.scopesToApprove)}" th:text="#{consent.none}">No additional permission.</p>
    <ul class="scopes">
      <li th:each="scope, status : ${consent.scopesToApprove}">
        <input type="checkbox" name="scope" th:id="${'scope-' + status.index}" th:value="${scope.name}" checked>
        <label th:for="${'scope-' + status.index}" th:text="${scope.description}">Scope</label>
      </li>
    </ul>
    <button type="submit" id="allow" th:text="#{consent.allow}">Allow</button>
  </form>
  <!-- denying posts no scope at all, which the authorization endpoint answers with error=access_denied -->
  <form method="post" th:action="@{${decisionPath}}">
    <input type="hidden" name="client_id" th:value="${consent.clientId}">
    <input type="hidden" name="state" th:value="${consent.state}">
    <input type="hidden" name="user_code" th:if="${userCode}" th:value="${userCode}">
    <button type="submit" id="deny" class="secondary" th:text="#{consent.deny}">Deny</button>
  </form>
  <section th:if="${!#lists.isEmpty(consent.approvedScopes)}">
    <p th:text="#{consent.previous}">You already granted these permissions:</p>
    <ul class="scopes">
      <li th:each="scope : ${consent.approvedScopes}" th:text="${scope.description}">Scope</li>
    </ul>
  </section>
</main>
</body>
</html>

ConsentController implements the generated ConsentPageApi: it looks the client up (an unknown one is a 400, rendered as the error page), reads the scopes the user granted earlier and renders the page.

    /**
     * Renders the consent page.
     *
     * @param clientId identifier of the client that asks for access.
     * @param scope    requested scopes, space delimited.
     * @param state    state of the authorization request.
     * @param userCode user code of the device the consent is asked for, {@code null} for an authorization request;
     *                 the decision of a device is posted to the device verification endpoint, with the code.
     * @return the consent page.
     * @throws ResponseStatusException with status 400 when the client is unknown.
     */
    @Override
    public ResponseEntity<String> consentPage(final String clientId, final String scope, final String state,
            final String userCode) {
        final var client = registeredClientRepository.findByClientId(clientId);
        if (client == null) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Unknown client");
        }
        final var principalName = request.getUserPrincipal().getName();
        final var consent = authorizationConsentService.findById(client.getId(), principalName);
        final Set<String> granted = consent == null ? Set.of() : consent.getScopes();
        final var model = new HashMap<String, Object>();
        model.put(CONSENT_ATTRIBUTE, mapper.toModel(client, principalName, state, scope, granted,
                RequestContextUtils.getLocale(request)));
        if (userCode == null) {
            model.put(DECISION_PATH_ATTRIBUTE, AUTHORIZE_PATH);
        } else {
            model.put(DECISION_PATH_ATTRIBUTE, DeviceVerificationPageApi.PATH_DEVICE_VERIFICATION_PAGE);
            model.put(USER_CODE_ATTRIBUTE, userCode);
        }
        return pageRenderer.render(VIEW_NAME, model);
    }
  /oauth2/consent:
    get:
      tags: [ Consent page ]
      operationId: consentPage
      summary: Renders the consent page
      description: >-
        Renders the page the authorization endpoint redirects to when a client needs the user's approval: the client,
        the requested scopes (as checkboxes, checked by default) and the scopes granted earlier. The decision is
        posted to the authorization endpoint (POST /oauth2/authorize), or to the device verification endpoint for a device,
        never to this operation.
      parameters:
        - name: client_id
          in: query
          required: true
          description: Identifier of the registered client that asks for access.
          schema:
            type: string
            minLength: 1
        - name: scope
          in: query
          required: true
          description: Requested scopes, space delimited as in the authorization request.
          schema:
            type: string
        - name: state
          in: query
          required: true
          description: State the authorization endpoint generated for the consent step, posted back with the decision.
          schema:
            type: string
            minLength: 1
        - name: user_code
          in: query
          required: false
          description: >-
            Present when the consent is asked for a device (OAuth 2.0 Device Authorization Grant): the user code of the
            request. The decision is then posted to the device verification endpoint (POST /oauth2/device_verification)
            instead, with this code.
          schema:
            type: string
            maxLength: 32
      responses:
        '200':
          description: The consent page.
          content:
            text/html:
              schema:
                type: string
        '400':
          description: >-
            The client is unknown or a parameter is missing; the error page is rendered, without any detail of the
            failure.
          content:
            text/html:
              schema:
                type: string

Logout

Mechanism Support Notes

RP-initiated logout (/connect/logout)

Supported

Provided by Spring Authorization Server with OpenID Connect enabled. A client may only send the user to a post_logout_redirect_uri listed in its registered postLogoutRedirectUris; any other is never honoured. They are seeded from authserver.clients.<client>.post-logout-redirect-uris (AUTHSERVER_BFF_POST_LOGOUT_REDIRECT_URIS, AUTHSERVER_SPA_POST_LOGOUT_REDIRECT_URIS) and are part of the clients API.

Back-channel logout

Not implemented

The server sends no logout_token to the clients, so a client session survives a sign-out of the server until it expires or the user signs out of the client too.

Front-channel logout

Not supported

Spring Authorization Server does not support it.

The server also has its own sign-out for users of its login pages: a confirmation page (logout.html) whose form posts to /logout. The POST carries the CSRF token (th:action adds it), so a third-party page cannot sign the user out; it invalidates the session, deletes the JSESSIONID cookie and returns to /login?logout.

<html xmlns:th="http://www.thymeleaf.org" th:replace="~{fragments/layout :: layout(~{::title}, ~{::main})}">
<head>
  <title th:text="#{logout.title}">Sign out</title>
</head>
<body>
<main>
  <h1 th:text="#{logout.heading}">Sign out</h1>
  <p th:text="#{logout.question}">Do you want to sign out?</p>
  <!-- th:action adds the CSRF token: the logout endpoint only accepts a POST that carries it -->
  <form method="post" th:action="@{/logout}">
    <button type="submit" id="logout" th:text="#{logout.confirm}">Sign out</button>
  </form>
</main>
</body>
</html>
    @Override
    public void customize(final HttpSecurity http) {
        http.logout(logout -> logout
                .logoutUrl(LOGOUT_PATH)
                .logoutSuccessUrl(LOGOUT_SUCCESS_URL)
                .invalidateHttpSession(true)
                .deleteCookies(SESSION_COOKIE));
    }

The confirmation page is the GET /logout operation of the pages contract (LogoutController); the POST belongs to Spring Security’s logout filter and is not part of it.

  /logout:
    get:
      tags: [ Logout page ]
      operationId: logoutPage
      summary: Renders the sign-out confirmation page
      description: >-
        Renders the page that asks the signed-in user to confirm signing out. A GET never signs the user out (any page
        could trigger it); the confirmation form posts to the security chain (POST /logout), with the CSRF token.
      responses:
        '200':
          description: The sign-out confirmation page.
          content:
            text/html:
              schema:
                type: string

Error page

Errors are answered by Spring Boot’s own BasicErrorController at /error, which belongs to the framework like the Spring Security endpoints, so it has no contract here. A browser gets templates/error.html through ErrorPageViewResolver, which picks a generic text from the status only (not found, forbidden, anything else) and adds the branding; the model the controller offers (timestamp, path, exception) is not passed on, so the page never shows a stack trace, an exception message or the requested path. A client that does not accept HTML gets the controller’s JSON body: spring.web.error.include-path: never leaves out the path, and the message, the exception and the stack trace are left out by default, so only the timestamp, the status and its reason phrase remain.

Backend for frontend

The bff (port 8080) is the only client the browser talks to. It serves the SPA (static files from its boot module), runs the authorization code flow with PKCE as a confidential client, keeps the user’s tokens in its server-side session and attaches the access token to the calls the SPA makes to the resource server. The browser holds nothing but a session cookie: the end-to-end test scans storage, cookies and response bodies to prove that no token is visible.

    /**
     * Builds the BFF filter chain.
     *
     * @param http                 the HTTP security builder.
     * @param clientRepository     the registered OAuth2 clients.
     * @param loginSuccessHandler  sends the browser back to the {@code returnTo} of the login once signed in.
     * @param logoutSuccessHandler redirects the browser to the RP-initiated logout of the authorization server.
     * @return the security filter chain.
     * @throws Exception if the chain cannot be built.
     */
    @Bean
    SecurityFilterChain bffFilterChain(final HttpSecurity http, final ClientRegistrationRepository clientRepository,
            final ReturnToAuthenticationSuccessHandler loginSuccessHandler,
            final OidcClientInitiatedLogoutSuccessHandler logoutSuccessHandler) throws Exception {
        final var defaultResolver = new DefaultOAuth2AuthorizationRequestResolver(clientRepository,
                "/oauth2/authorization");
        // The auth server requires PKCE; Spring only enables it by default for public clients.
        defaultResolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce());
        // A login started for step-up (GET /bff/login with acrValues / maxAge) also asks for acr_values and max_age.
        final var resolver = new StepUpAuthorizationRequestResolver(defaultResolver);

        http.authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/", "/index.html", "/favicon.ico", "/assets/**", "/static/**", "/error",
                                "/bff/login", "/actuator/health/**").permitAll()
                        .anyRequest().authenticated())
                // The XSRF-TOKEN cookie is readable by the script (not HttpOnly) and the raw token is accepted from
                // the X-XSRF-TOKEN header or, for the sign-out form, from the _csrf parameter. The plain handler, not
                // csrf.spa()'s XOR one: masking against BREACH protects a token rendered in a compressed response body,
                // and the BFF never renders it in a body, only in the cookie; the XOR handler would also reject the
                // raw cookie value the sign-out form posts.
                .csrf(csrf -> csrf
                        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                        .csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler()))
                // The SPA is made of same-origin files only: no inline script, no third-party content, no framing.
                .headers(headers -> headers.contentSecurityPolicy(
                        csp -> csp.policyDirectives(CONTENT_SECURITY_POLICY)))
                .addFilterAfter(new CsrfCookieFilter(), CsrfFilter.class)
                .exceptionHandling(ex -> ex.defaultAuthenticationEntryPointFor(
                        new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED),
                        new OrRequestMatcher(PathPatternRequestMatcher.withDefaults().matcher("/bff/**"),
                                PathPatternRequestMatcher.withDefaults().matcher("/api/**"))))
                .oauth2Login(login -> login
                        .authorizationEndpoint(endpoint -> endpoint.authorizationRequestResolver(resolver))
                        // A refused consent or any other failed sign-in lands on the SPA, which tells the user.
                        // A handler rather than failureUrl: that would make the generated login page answer it.
                        .failureHandler(new SimpleUrlAuthenticationFailureHandler(SIGN_IN_FAILURE_URL))
                        // Back to the returnTo validated by GET /bff/login, never to a request saved elsewhere.
                        .successHandler(loginSuccessHandler))
                // POST /bff/logout (CSRF protected) runs the logout handlers (the XSRF-TOKEN cookie is cleared, the
                // security context too, and the session is invalidated), then the success handler answers 302 to the
                // end_session_endpoint of the authorization server: the browser follows it as a top-level navigation,
                // so the id_token_hint it carries never reaches a script.
                .logout(logout -> logout
                        .logoutRequestMatcher(PathPatternRequestMatcher.withDefaults()
                                .matcher(HttpMethod.POST, LOGOUT_PATH))
                        .logoutSuccessHandler(logoutSuccessHandler));
        return http.build();
    }

Requests under /bff/ and /api/ that are not authenticated get a 401 instead of a redirect, so the SPA can decide what to do. A failed or denied sign-in redirects to /?error=signin; a successful one goes back to the returnTo of the login (see below). The BFF chain sets the same content security policy as the login pages (without the logo’s image source: the SPA has no logo).

The HTTP session is stored in PostgreSQL by Spring Session JDBC, in the bff database. The schema is owned by Flyway (V300__spring_session.sql; Spring Session never creates it). The session holds the authorized client, that is, the access and refresh tokens (HttpSessionOAuth2AuthorizedClientRepository), so the sessions survive a restart and the tokens never leave the server.

Session persistence is a driven adapter: the module bff/infrastructure/session holds the migration, the session configuration and the JDBC, Flyway and PostgreSQL dependencies (the enforcer rules ban spring-jdbc from api/web). Spring Boot auto-configures Spring Session JDBC from spring-boot-starter-session-jdbc, so every spring.session.* property applies (spring.session.jdbc.initialize-schema: never, spring.session.timeout, …​). The configuration deliberately has no @EnableJdbcHttpSession, which would switch that auto-configuration off and silently ignore those properties.

CREATE TABLE SPRING_SESSION (
    PRIMARY_ID            CHAR(36) NOT NULL,
    SESSION_ID            CHAR(36) NOT NULL,
    CREATION_TIME         BIGINT   NOT NULL,
    LAST_ACCESS_TIME      BIGINT   NOT NULL,
    MAX_INACTIVE_INTERVAL INT      NOT NULL,
    EXPIRY_TIME           BIGINT   NOT NULL,
    PRINCIPAL_NAME        VARCHAR(100),
    CONSTRAINT SPRING_SESSION_PK PRIMARY KEY (PRIMARY_ID)
);

CREATE UNIQUE INDEX SPRING_SESSION_IX1 ON SPRING_SESSION (SESSION_ID);
CREATE INDEX SPRING_SESSION_IX2 ON SPRING_SESSION (EXPIRY_TIME);
CREATE INDEX SPRING_SESSION_IX3 ON SPRING_SESSION (PRINCIPAL_NAME);

CREATE TABLE SPRING_SESSION_ATTRIBUTES (
    SESSION_PRIMARY_ID CHAR(36)     NOT NULL,
    ATTRIBUTE_NAME     VARCHAR(200) NOT NULL,
    ATTRIBUTE_BYTES    BYTEA        NOT NULL,
    CONSTRAINT SPRING_SESSION_ATTRIBUTES_PK PRIMARY KEY (SESSION_PRIMARY_ID, ATTRIBUTE_NAME),
    CONSTRAINT SPRING_SESSION_ATTRIBUTES_FK FOREIGN KEY (SESSION_PRIMARY_ID)
        REFERENCES SPRING_SESSION (PRIMARY_ID) ON DELETE CASCADE
);

The cookie is Host-SESSION: Secure, HttpOnly, SameSite=Lax, Path=/ and no Domain, which is exactly what the Host- prefix makes browsers require. Chromium accepts Secure cookies on http://localhost, so local development works over plain HTTP through localhost.

    /**
     * Builds the serializer of the session cookie: Secure, HttpOnly, SameSite=Lax, path {@code /} and no domain, which
     * is exactly what the {@code __Host-} prefix demands (the browser rejects the cookie otherwise).
     *
     * @return the cookie serializer.
     */
    @Bean
    CookieSerializer cookieSerializer() {
        final var serializer = new DefaultCookieSerializer();
        serializer.setCookieName(COOKIE_NAME);
        serializer.setUseSecureCookie(true);
        serializer.setUseHttpOnlyCookie(true);
        serializer.setSameSite("Lax");
        serializer.setCookiePath("/");
        return serializer;
    }

In the dev profile the datasource comes from the root compose.yaml, whose connection details always name the authserver database; BffDevDatabase (dev profile only, in the same module) points them at the bff database the init script creates.

    /**
     * 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;
    }

CSRF

CookieCsrfTokenRepository.withHttpOnlyFalse() stores the token in the XSRF-TOKEN cookie, readable by scripts, and a plain CsrfTokenRequestAttributeHandler accepts the raw token from the X-XSRF-TOKEN request header or from the _csrf form parameter. Spring Security loads the token lazily, so CsrfCookieFilter reads it on every request to make sure the cookie is always written. A script copies the cookie into the header of a state-changing fetch; the sign-out form, which cannot send a header, copies it into _csrf.

csrf.spa() is not used: it resolves a form parameter with the XOR handler, which expects a BREACH-masked token and would reject the raw cookie value the sign-out form posts. That masking protects a token rendered inside a compressed response body, where a BREACH attack can recover it byte by byte. The BFF never renders the token in a body, only in the cookie, so the plain handler loses nothing.

const XSRF_COOKIE = 'XSRF-TOKEN';
const XSRF_PARAMETER = '_csrf';

/** Media types the documents API answers: its JSON results and its problem details. */
const JSON_OR_PROBLEM = 'application/json, application/problem+json';

/**
 * Finds an element of the page by its id.
 *
 * @param {string} id the id of the element.
 * @returns {HTMLElement} the element.
 */
const element = (id) => document.getElementById(id);

/**
 * Reads a cookie the script is allowed to see (the session cookie is HttpOnly and never visible).
 *
 * @param {string} name the name of the cookie.
 * @returns {string} the decoded value, or an empty string if the cookie is missing.
 */
const readCookie = (name) => {
    const prefix = `${name}=`;
    const entry = document.cookie.split('; ').find((cookie) => cookie.startsWith(prefix));
    return entry ? decodeURIComponent(entry.substring(prefix.length)) : '';
};

/**
 * Shows an error in the live region the screen readers announce, or clears it.
 *
 * @param {string} message the message, or an empty string to clear it.
 */
const showError = (message) => {
    const error = element('error');
    error.textContent = message;
    error.hidden = message === '';
};

/**
 * Sends the browser to the BFF login, asking to come back to the current page afterwards.
 */
const login = () => {
    const returnTo = window.location.pathname === '/index.html' ? '/index.html' : '/';
    window.location.assign(`/bff/login?returnTo=${encodeURIComponent(returnTo)}`);
};

/**
 * Shows the signed-out state, with the button that starts the sign-in. Nothing is started automatically: right after a
 * sign-out the authorization server sends the browser back here, and an automatic redirect would sign it in again.
 */
const showSignedOut = () => {
    element('status').textContent = 'You are signed out.';
    element('profile').hidden = true;
    element('documents').hidden = true;
    element('signed-out').hidden = false;
};

/**
 * Fills the profile card with the signed-in user.
 *
 * @param {{subject: string, name: string, email: string, roles: string[]}} user the user of the session.
 */
const showProfile = (user) => {
    element('profile-name').textContent = user.name ?? '';
    element('profile-email').textContent = user.email ?? '';
    element('profile-subject').textContent = user.subject ?? '';
    element('profile-roles').textContent = (user.roles ?? []).join(', ');
    element('status').textContent = `Signed in as ${user.name || user.subject}.`;
    element('profile').hidden = false;
};

/**
 * Renders the documents the API returned.
 *
 * @param {{id: string, title: string, content: string}[]} documents the documents.
 */
const showDocuments = (documents) => {
    const list = element('documents-list');
    list.replaceChildren(...documents.map((doc) => {
        const item = window.document.createElement('li');
        const title = window.document.createElement('strong');
        title.textContent = doc.title;
        item.append(title, `: ${doc.content}`);
        return item;
    }));
    element('documents-empty').hidden = documents.length > 0;
    element('documents').hidden = false;
};

/**
 * Asks the BFF for the user of the session, and shows the signed-out state when there is none.
 */
const loadUser = async () => {
    const response = await fetch('/bff/user', {credentials: 'same-origin', headers: {Accept: 'application/json'}});
    if (response.status === 401) {
        showSignedOut();
        return;
    }
    if (!response.ok) {
        throw new Error(`The session could not be read (${response.status}).`);
    }
    showProfile(await response.json());
};

/**
 * Loads the documents through the BFF, which asks the resource server with the access token of the user. A 401 here
 * means the session of a signed-in user has ended (or its token could not be renewed), so the sign-in starts again.
 */
const loadDocuments = async () => {
    showError('');
    // The BFF answers its failures as RFC 9457 problem details; asking for both types gets application/problem+json.
    const response = await fetch('/api/documents', {credentials: 'same-origin', headers: {Accept: JSON_OR_PROBLEM}});
    if (response.status === 401) {
        login();
        return;
    }
    if (!response.ok) {
        throw new Error(`The documents could not be loaded (${response.status}).`);
    }
    showDocuments(await response.json());
};

/**
 * Signs out with a top-level form POST, so that the browser itself follows the redirect of the BFF to the logout of the
 * authorization server: that URL carries the ID token hint, which a script must never read. A form cannot send a
 * header, so the CSRF token travels as the _csrf parameter.
 */
const signOut = () => {
    showError('');
    const form = window.document.createElement('form');
    form.method = 'post';
    form.action = '/bff/logout';
    form.hidden = true;
    const token = window.document.createElement('input');
    token.type = 'hidden';
    token.name = XSRF_PARAMETER;
    token.value = readCookie(XSRF_COOKIE);
    form.append(token);
    window.document.body.append(form);
    form.submit();
};

/**
 * Runs an action from a button, disabling it meanwhile and reporting a failure in the live region.
 *
 * @param {HTMLButtonElement} button the button that triggered the action.
 * @param {() => Promise<void>} action the action.
 */
const run = async (button, action) => {
    button.disabled = true;
    try {
        await action();
    } catch (error) {
        showError(error.message);
    } finally {
        button.disabled = false;
    }
};

const loadButton = element('load-documents');
const signOutButton = element('sign-out');
const signInButton = element('sign-in');
loadButton.addEventListener('click', () => run(loadButton, loadDocuments));
signOutButton.addEventListener('click', () => run(signOutButton, async () => signOut()));
signInButton.addEventListener('click', login);

// The heading takes the focus so a screen reader starts reading from the top of the page.
element('main-heading').focus();
if (new URLSearchParams(window.location.search).has('error')) {
    // The sign-in failed or was cancelled (for example, the consent was denied): say so instead of looping to the login.
    element('status').textContent = '';
    showError('Sign-in failed or was cancelled. No session was created.');
    element('retry').hidden = false;
} else {
    loadUser().catch((error) => {
        element('status').textContent = '';
        showError(error.message);
    });
}

Login and logout API

GET /bff/login?returnTo= starts the sign-in. returnTo is only accepted when it is an allow-listed relative path (bff.login.allowed-return-paths, an entry ending in / also allows what is below it), otherwise the answer is 400; this prevents an open redirect. The accepted target is kept in a session attribute owned by the BFF, and the browser is redirected to the authorization request. Once the OAuth2 login succeeds, ReturnToAuthenticationSuccessHandler reads and removes that attribute, validates it again and redirects there, or to / when it is absent or not allowed. A request saved by Spring Security for any other reason is never used as a target.

The login also takes the optional acrValues and maxAge parameters, used to answer a step-up request of the resource server (see Step-up through the BFF). The contract checks their format (authentication context class references separated by spaces, and a number of seconds from 0 to 86400), and BffLoginController keeps them in the session as StepUpLoginParameters. StepUpAuthorizationRequestResolver wraps the PKCE-enabled DefaultOAuth2AuthorizationRequestResolver of the chain: it adds them to the next authorization request as the OpenID Connect acr_values and max_age parameters and then removes them, so they apply to one login only.

    /**
     * Validates {@code returnTo}, keeps it in the session for {@link ReturnToAuthenticationSuccessHandler}, which sends
     * the browser there once the OAuth2 login succeeds, keeps the step-up values (if any) for
     * {@link StepUpAuthorizationRequestResolver}, which adds them to the authorization request, and redirects to the
     * authorization request. The format and range of {@code acrValues} and {@code maxAge} are checked by the generated
     * interface.
     *
     * @param returnTo  relative path to return to after the login; the root of the application when absent.
     * @param acrValues authentication context classes to ask the authorization server for; none when absent.
     * @param maxAge    maximum age, in seconds, of the authentication to ask for; none when absent.
     * @return a redirect to the authorization request.
     * @throws ResponseStatusException answered 400 when {@code returnTo} is not an allowed relative path.
     */
    @Override
    public ResponseEntity<Void> login(final String returnTo, final String acrValues, final Long maxAge) {
        final var target = StringUtils.hasText(returnTo) ? returnTo : DEFAULT_RETURN_TO;
        if (!returnToValidator.isAllowed(target)) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "returnTo is not an allowed relative path");
        }
        final var session = request.getSession();
        session.setAttribute(ReturnToAuthenticationSuccessHandler.RETURN_TO_ATTRIBUTE, target);
        if (StringUtils.hasText(acrValues) || maxAge != null) {
            session.setAttribute(StepUpAuthorizationRequestResolver.STEP_UP_ATTRIBUTE,
                    new StepUpLoginParameters(StringUtils.hasText(acrValues) ? acrValues : null, maxAge));
        } else {
            session.removeAttribute(StepUpAuthorizationRequestResolver.STEP_UP_ATTRIBUTE);
        }
        return ResponseEntity.status(HttpStatus.FOUND).location(URI.create(AUTHORIZATION_PATH)).build();
    }
/**
 * Sends the browser, once the OAuth2 login has succeeded, back to the {@code returnTo} that {@link BffLoginController}
 * validated and kept in the session. The attribute is read once and removed, and validated again by
 * {@link ReturnToValidator} before it is used, so a value that reached the session any other way can never become an
 * open redirect; when it is absent or not allowed, the browser goes to the root of the application.
 */
@Component
@RequiredArgsConstructor
public class ReturnToAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    /** Session attribute, owned by the BFF, holding the validated {@code returnTo} of the login in progress. */
    public static final String RETURN_TO_ATTRIBUTE = ReturnToAuthenticationSuccessHandler.class.getName()
            + ".RETURN_TO";

    /** Where the browser goes when there is no allowed {@code returnTo}: the root of the application. */
    static final String DEFAULT_TARGET = "/";

    /** Decides which {@code returnTo} values are safe. */
    private final ReturnToValidator returnToValidator;

    /**
     * Takes the {@code returnTo} out of the session and decides where the browser goes.
     *
     * @param request        the request of the login callback.
     * @param response       the response.
     * @param authentication the new authentication.
     * @return the validated {@code returnTo}, or {@link #DEFAULT_TARGET}.
     */
    @Override
    protected String determineTargetUrl(final HttpServletRequest request, final HttpServletResponse response,
            final Authentication authentication) {
        final var session = request.getSession(false);
        if (session == null) {
            return DEFAULT_TARGET;
        }
        final var returnTo = session.getAttribute(RETURN_TO_ATTRIBUTE);
        session.removeAttribute(RETURN_TO_ATTRIBUTE);
        return returnTo instanceof String target && returnToValidator.isAllowed(target) ? target : DEFAULT_TARGET;
    }
}

POST /bff/logout (CSRF protected) is answered by Spring Security’s logout filter, configured in the BFF chain. Its handlers clear the XSRF-TOKEN cookie and the security context and invalidate the session (which deletes it from the spring_session table); then OidcClientInitiatedLogoutSuccessHandler answers 302 to the authorization server’s end_session_endpoint, with id_token_hint and post_logout_redirect_uri: this is the RP-initiated logout of the table above. The SPA signs out with a top-level form submission, so the browser itself follows that redirect: the ID token in the URL is part of a navigation, never of a response a script can read. The authorization server ends its own session and sends the browser back to the root of the SPA, which shows its signed-out state.

                // POST /bff/logout (CSRF protected) runs the logout handlers (the XSRF-TOKEN cookie is cleared, the
                // security context too, and the session is invalidated), then the success handler answers 302 to the
                // end_session_endpoint of the authorization server: the browser follows it as a top-level navigation,
                // so the id_token_hint it carries never reaches a script.
                .logout(logout -> logout
                        .logoutRequestMatcher(PathPatternRequestMatcher.withDefaults()
                                .matcher(HttpMethod.POST, LOGOUT_PATH))
                        .logoutSuccessHandler(logoutSuccessHandler));
    /**
     * Builds the handler that redirects the browser to the logout URL of the authorization server (its
     * {@code end_session_endpoint}, with {@code id_token_hint} and {@code post_logout_redirect_uri}), with the default
     * redirect strategy: the answer to {@code POST /bff/logout} is a {@code 302} that the browser follows as a
     * top-level navigation, so no script ever reads the ID token the URL carries.
     *
     * @param clientRepository the registered OAuth2 clients.
     * @return the logout success handler.
     */
    @Bean
    OidcClientInitiatedLogoutSuccessHandler oidcLogoutSuccessHandler(
            final ClientRegistrationRepository clientRepository) {
        final var handler = new OidcClientInitiatedLogoutSuccessHandler(clientRepository);
        handler.setPostLogoutRedirectUri(POST_LOGOUT_REDIRECT_URI);
        return handler;
    }

The login, the user endpoint and the documents API are defined by the contract apis/bff/rest-server/bff-api-v1.yaml. The logout is not: like the OAuth 2.0 login endpoints, it is answered by Spring Security itself.

  /bff/login:
    get:
      tags: [ Login ]
      operationId: login
      summary: Starts the login
      description: >-
        Redirects the browser to the OpenID Connect authorization request of the authorization server. Once the user
        has signed in, the BFF sends the browser back to returnTo (or to the root of the application when it is
        absent). The SPA navigates to this endpoint; it is not called through fetch.
      security: [ ]
      parameters:
        - name: returnTo
          in: query
          required: false
          description: >-
            Relative path (with an optional query string) of the SPA page to return to after the login. It must be
            one of the paths listed in bff.login.allowed-return-paths; anything else (absolute URLs, scheme-relative
            URLs starting with //, backslashes, control characters) is rejected to prevent open redirects.
          schema:
            type: string
            maxLength: 2048
            examples:
              - /orders
        - name: acrValues
          in: query
          required: false
          description: >-
            Space-separated authentication context class references the authorization server must satisfy, sent as
            the acr_values parameter of the authorization request. The SPA copies it from the acrValues of a
            step-up-required problem (RFC 9470) so the user signs in again with a strong enough authentication.
            Absent, the authorization request carries no acr_values.
          schema:
            type: string
            maxLength: 512
            pattern: '^[A-Za-z0-9:._~/-]+( [A-Za-z0-9:._~/-]+)*$'
            examples:
              - urn:irurueta:acr:mfa
        - name: maxAge
          in: query
          required: false
          description: >-
            Maximum age, in seconds, of the user's authentication, sent as the max_age parameter of the authorization
            request: an older sign-in makes the authorization server ask the user to authenticate again. The SPA
            copies it from the maxAge of a step-up-required problem. Absent, the authorization request carries no
            max_age.
          schema:
            type: integer
            format: int64
            minimum: 0
            maximum: 86400
            examples:
              - 300
      responses:
        '302':
          description: Redirect to the authorization request of the authorization server
          headers:
            Location:
              description: URL of the authorization request, /oauth2/authorization/bff
              schema:
                type: string
        '400':
          description: >-
            returnTo is not an allowed relative path, or acrValues or maxAge is not valid

Documents API

The SPA reads and deletes the user’s documents through the BFF: GET /api/documents and DELETE /api/documents/{id} are operations of the BFF’s own contract, with the same schema and status codes as the resource server’s, plus 401 (no session, no valid token, or a step-up request) and 502 (the resource server is unreachable or failed). The BFF’s registration asks for both documents.read and documents.delete (property spring.security.oauth2.client.registration.bff.scope), because each operation of the resource server needs its own scope; the seeded bff client allows both and the user grants them on the consent page. There is no pass-through relay: OpenAPI has no wildcard paths, and every operation the browser can call is described, generated and checked by OpenApiDriftIT like any other.

  /api/documents:
    get:
      tags: [ Documents ]
      operationId: listDocuments
      summary: Lists documents
      description: >-
        Lists the documents of the signed-in user; an administrator sees all. The BFF asks the resource server
        (GET /api/documents there, which needs the scope documents.read) with the access token of the session,
        renewing it with the refresh token when it expired.
      security:
        - session: [ ]
      responses:
        '200':
          description: The documents.
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/DocumentResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: The access token of the session lacks the documents.read scope.
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
            application/json:
              schema:
                $ref: '#/components/schemas/Problem'
        '502':
          $ref: '#/components/responses/BadGateway'
  /api/documents/{id}:
    delete:
      tags: [ Documents ]
      operationId: deleteDocument
      summary: Deletes a document
      description: >-
        Deletes one of the signed-in user's documents; an administrator may delete any. The BFF asks the resource
        server (DELETE /api/documents/{id} there, which needs the scope documents.delete and a recent strong
        authentication) with the access token of the session. Someone else's document is answered 404, like a missing
        one. A state-changing request: it needs the CSRF token.
      security:
        - session: [ ]
          csrf: [ ]
      parameters:
        - name: id
          in: path
          required: true
          description: Unique identifier of the document.
          schema:
            type: string
      responses:
        '204':
          description: The document was deleted.
        '401':
          description: >-
            There is no signed-in session (answered by the security chain, without a body), or the session holds no
            valid access token (type urn:problem:documents:unauthorized: the SPA signs the user in again), or the
            resource server asks for step-up authentication (RFC 9470) because the session's sign-in is not strong or
            recent enough (type urn:problem:documents:step-up-required, with acrValues and maxAge: the SPA sends the
            user to GET /bff/login with those values, then retries).
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
            application/json:
              schema:
                $ref: '#/components/schemas/Problem'
        '403':
          description: >-
            The request lacks the CSRF token (answered by the security chain, without a body), or the access token
            of the session lacks the documents.delete scope.
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
            application/json:
              schema:
                $ref: '#/components/schemas/Problem'
        '404':
          description: The document does not exist or belongs to someone else.
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
            application/json:
              schema:
                $ref: '#/components/schemas/Problem'
        '502':
          $ref: '#/components/responses/BadGateway'

The BFF is hexagonal like the other applications. DocumentsController implements the generated DocumentsApi and calls the use cases (ListDocumentsUseCase, DeleteDocumentUseCase in bff/application), mapping the domain Document onto the generated DTO (DocumentDtoMapper); a scoped @RestControllerAdvice answers the domain exceptions as problem details.

    /**
     * Lists the documents of the signed-in user.
     *
     * @return the documents.
     */
    @Override
    public ResponseEntity<List<DocumentResponse>> listDocuments() {
        return ResponseEntity.ok(listDocumentsUseCase.execute().stream().map(documentDtoMapper::toResponse).toList());
    }

    /**
     * Deletes a document of the signed-in user.
     *
     * @param id identifier of the document.
     * @return an empty {@code 204}.
     */
    @Override
    public ResponseEntity<Void> deleteDocument(final String id) {
        deleteDocumentUseCase.execute(id);
        return ResponseEntity.noContent().build();
    }

The use cases only see the domain port DocumentGateway (bff/domain). Its implementation, RestDocumentGateway in the driven adapter bff/infrastructure/resourceserver, calls the resource server through a client generated from the resource server’s own contract (apis/resource-server/rest-server/resource-server-api-v1.yaml, java generator with the restclient library) and translates every failure into a domain exception: a token that cannot be obtained or renewed, or a 401 of the resource server, is unauthorized (401, so the SPA signs in again), except a 401 whose challenge asks for step-up (below); a 403 is forbidden; a 404 is not found; an unreachable resource server or any other answer is unavailable (502). No HTTP or OAuth2 type crosses the port, and nothing the resource server answers (headers, cookies, error bodies) reaches the browser: the BFF builds its own responses. The one exception is the acr_values and max_age of a step-up challenge, which the browser needs to sign in again; they are kept within what GET /bff/login accepts (below). The problems are answered as application/problem+json; the operations also declare them under application/json and the handler does not force the media type, so a client that only accepts JSON gets the status and the problem instead of 406.

    @Override
    public List<Document> list() {
        final var documents = call(documentsApi::listDocuments);
        return documents == null ? List.of() : documents.stream().map(documentMapper::toDomain).toList();
    }

    @Override
    public void deleteById(final String id) {
        call(() -> documentsApi.deleteDocumentWithHttpInfo(id));
    }

    /**
     * Calls the resource server and translates its failures into domain exceptions.
     *
     * @param operation the call.
     * @param <T>       type of the answer.
     * @return the answer of the resource server.
     */
    private <T> T call(final Supplier<T> operation) {
        try {
            return operation.get();
        } catch (final OAuth2AuthorizationException e) {
            log.warn("No access token for the resource server: {}", e.getError().getErrorCode());
            throw new DocumentsUnauthorizedException("The session has no valid token", e);
        } catch (final RestClientResponseException e) {
            throw translate(e);
        } catch (final RestClientException e) {
            log.warn("The resource server cannot be reached: {}", e.getClass().getSimpleName());
            throw new DocumentsUnavailableException("The resource server is unavailable", e);
        }
    }

The generated client runs on a RestClient built from Spring Boot’s RestClient.Builder with Spring Security’s OAuth2ClientHttpRequestInterceptor: it asks the authorized client manager (declared by the BFF’s security configuration) for the access token of the user of the session, renewing it with the refresh token when it expired, and sends it as bearer token; the browser never sends or sees it. The interceptor lets a call through unauthenticated when the session has no authorized client, so a second interceptor stops that call: the BFF never sends a request without a token. The base URI is bff.resource-server.base-uri (RESOURCE_SERVER_URI).

    /**
     * Builds the REST client of the resource server. Its interceptor asks the authorized client manager for the access
     * token of the user of the current request (renewing it with the refresh token when it expired) and sets it as the
     * bearer token of the outgoing request; a call whose session has no token is never sent. When the token cannot be
     * obtained or renewed it throws an {@link org.springframework.security.oauth2.core.OAuth2AuthorizationException},
     * which {@link RestDocumentGateway} reports as {@link
     * com.irurueta.authserver.bff.domain.documents.DocumentsUnauthorizedException}, answered 401 so the SPA signs in
     * again.
     *
     * @param builder the builder of REST clients, the one test slices bind a mock server to.
     * @param manager the manager of the authorized clients of the session.
     * @return the REST client of the resource server.
     */
    @Bean
    RestClient resourceServerRestClient(final RestClient.Builder builder, final OAuth2AuthorizedClientManager manager) {
        final var interceptor = new OAuth2ClientHttpRequestInterceptor(manager);
        interceptor.setClientRegistrationIdResolver(request -> REGISTRATION_ID);
        // The OAuth2 interceptor lets the call through unauthenticated when the session has no authorized client;
        // the BFF must never do that, so the call stops here and the SPA gets a 401.
        return builder.requestInterceptor(interceptor).requestInterceptor((request, body, execution) -> {
            if (!request.getHeaders().containsHeader(HttpHeaders.AUTHORIZATION)) {
                throw new ClientAuthorizationException(new OAuth2Error(OAuth2ErrorCodes.ACCESS_DENIED,
                        "The session has no access token", null), REGISTRATION_ID);
            }
            return execution.execute(request, body);
        }).build();
    }
    /**
     * Builds the documents client generated from the resource server's contract, on top of the REST client that
     * carries the user's token (so the generated client's own authentication settings stay unused).
     *
     * @param resourceServerRestClient the REST client of the resource server.
     * @param properties               where the resource server is.
     * @return the generated documents client.
     */
    @Bean
    DocumentsApi resourceServerDocumentsApi(final RestClient resourceServerRestClient,
            final ResourceServerProperties properties) {
        final var apiClient = new ApiClient(resourceServerRestClient)
                .setBasePath(properties.baseUri().toString().replaceFirst("/+$", ""));
        return new DocumentsApi(apiClient);
    }

Step-up through the BFF

Deleting a document needs a recent multi-factor sign-in at the resource server (see Resource server and Multi-factor authentication and step-up). When the token of the session does not prove one, the resource server answers 401 with WWW-Authenticate: Bearer error="insufficient_user_authentication", acr_values="…​", max_age="…​". StepUpChallengeMapper reads that challenge (any other 401 stays unauthorized) and RestDocumentGateway throws the domain exception DocumentsStepUpRequiredException with its values. DocumentsExceptionHandler answers it as a 401 problem of type urn:problem:documents:step-up-required with the extra members acrValues and maxAge (seconds). StepUpProblemMapper keeps them within what the login accepts: references of another format are dropped, and a maxAge above one day is capped at one day, which is stricter than the resource server asked for, so the new sign-in still satisfies it:

{
  "type": "urn:problem:documents:step-up-required",
  "status": 401,
  "detail": "The operation needs a stronger or more recent sign-in",
  "acrValues": "urn:irurueta:acr:mfa",
  "maxAge": 300
}

The client then navigates to /bff/login?returnTo=…​&acrValues=…​&maxAge=…​ with those values. The authorization server, receiving acr_values and max_age, sends the user to its second-factor page (or to sign in again when the sign-in is too old), and the new tokens carry acr = urn:irurueta:acr:mfa and a fresh auth_time, which the resource server accepts. The shipped SPA lists documents but has no delete button (the resource server starts with no documents), so this path is exercised through the API: DocumentsApiIT, SecurityConfigIT and the end-to-end BffEndToEndIT.documentDelete_whenSignInIsNotStrongEnough_asksForStepUpThroughTheLogin.

The single page application

The SPA is index.html plus assets/app.js, served by the BFF itself so that everything is same-origin, which the content security policy requires (no inline script). It asks GET /bff/user for the session and shows either the profile or, on a 401, a signed-out state with a Sign in button that goes to /bff/login?returnTo=…​. It never starts the sign-in by itself when the page loads: the authorization server sends the browser back to the SPA after a sign-out, and an automatic redirect would sign the user straight back in. A 401 from /api/documents during a signed-in session (the session ended, or its token could not be renewed) does start the sign-in again. The SPA signs out by building a <form method="post" action="/bff/logout"> with a hidden _csrf input set from the XSRF-TOKEN cookie and submitting it.

The end-to-end test BffEndToEndIT clicks Sign in, signs in through the login and consent pages, signs out, checks that the browser lands back on the signed-out SPA and that /bff/user and /api/documents answer 401, and scans every response of the whole flow, the storages and the cookies for tokens. Bodies, storages and cookies must be strictly token-free; the only exclusions from the header and URL scan are the Location of the 302 answering POST /bff/logout and the URL of the /connect/logout request, which carry id_token_hint by OpenID Connect design in a top-level navigation no script can read.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Auth server example</title>
    <link rel="stylesheet" href="/assets/styles.css">
    <script type="module" src="/assets/app.js"></script>
</head>
<body>
<main>
    <h1 id="main-heading" tabindex="-1">Auth server example</h1>

    <p id="status" role="status" aria-live="polite">Checking your session&hellip;</p>
    <p id="error" class="error" role="alert" aria-live="assertive" hidden></p>
    <p id="retry" hidden><a href="/bff/login?returnTo=%2F">Try signing in again</a></p>

    <section id="signed-out" aria-labelledby="signed-out-heading" hidden>
        <h2 id="signed-out-heading">You are signed out</h2>
        <p>Sign in to see your profile and your documents.</p>
        <div class="actions">
            <button type="button" id="sign-in">Sign in</button>
        </div>
    </section>

    <section id="profile" aria-labelledby="profile-heading" hidden>
        <h2 id="profile-heading">Your profile</h2>
        <dl>
            <dt>Name</dt>
            <dd id="profile-name"></dd>
            <dt>Email</dt>
            <dd id="profile-email"></dd>
            <dt>Subject</dt>
            <dd id="profile-subject"></dd>
            <dt>Roles</dt>
            <dd id="profile-roles"></dd>
        </dl>
        <div class="actions">
            <button type="button" id="load-documents">Load documents</button>
            <button type="button" id="sign-out">Sign out</button>
        </div>
    </section>

    <section id="documents" aria-labelledby="documents-heading" hidden>
        <h2 id="documents-heading">Documents</h2>
        <p id="documents-empty" hidden>You have no documents.</p>
        <ul id="documents-list"></ul>
    </section>
</main>
</body>
</html>