Architecture

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

Hexagonal layout

Each application is a Maven sub-reactor split into modules by hexagonal layer. The layering is enforced twice: by maven-enforcer-plugin bannedDependencies rules in each module’s pom.xml (jar granularity) and by a HexagonalArchitectureTest (ArchUnit) in each application’s boot module (package granularity).

<app>/                          aggregator pom, artifactId <app>-parent
  domain/                       <app>-domain
  application/                  <app>-application
  infrastructure/<adapter>/     <app>-infrastructure-<adapter>   (driven adapters: persistence, keys, ...)
  api/<adapter>/                <app>-api-<adapter>              (driving adapters: web, ...)
  boot/                         <app>-boot                       (composition root, the only runnable artifact)
Module May depend on Must not contain

domain

Nothing but the JDK (and Lombok, compile-only)

Spring, Jackson, JPA/JDBC or Spring Security types

application

domain and Spring (use cases are @Service beans found by component scanning)

Spring Security types, or any infrastructure/ or api/ module

infrastructure/*

domain, application

A sibling adapter or any api/* module

api/*

domain, application

Any infrastructure/* module

boot

Everything

Business logic: it only wires beans, holds application*.yml and the integration tests

A layer is only created once it has code: bff has domain (the documents and their DocumentGateway port), application (the documents use cases), infrastructure/session (the Spring Session JDBC store, its cookie and its Flyway migration), infrastructure/resourceserver (the generated client of the resource server behind the port), api/web (the security, login, logout, user and documents adapters) and boot (the SPA); resource-server has domain, application, infrastructure/memory and api/web; auth-server has infrastructure/persistence, infrastructure/keys, infrastructure/mail, infrastructure/sms and infrastructure/github (the generated client of GitHub’s /user/emails behind the VerifiedEmailLookup port); and service-client is a single boot module. A port is an interface in domain (for example UserAccountRepository); its implementation lives in an infrastructure/ adapter. Domain models are never returned from a controller: the api/ adapter maps them onto its own DTOs. Spring Security and Spring Authorization Server types are framework adapters and live in api/ or infrastructure/.

Every HTTP endpoint the applications handle themselves, JSON or HTML page, is contract first. The OpenAPI contracts live under apis/ at the repository root: apis/<app>/rest-server/<app>-api-v1.yaml for the JSON APIs and apis/auth-server/web-pages/auth-server-pages-v1.yaml for the login, consent and logout pages. openapi-generator turns them into Spring interfaces (and DTO records) in the api/web module at build time (target/generated-sources, never committed), and the hand-written controllers only implement those interfaces by calling use cases: no hand-written class carries a mapping annotation. A @Component mapper per feature (for example ClientDtoMapper) converts between the generated DTOs and the domain. A page’s generated method answers text/html; its controller renders the Thymeleaf template with PageRenderer, which resolves the view with the request’s locale and renders it against the current request, so CSRF fields, links and messages keep working.

    /**
     * Renders a page.
     *
     * @param viewName name of the view (the Thymeleaf template).
     * @param model    model attributes of the page; the branding is added to them.
     * @return a {@code 200} with the page as {@code text/html}.
     * @throws IllegalStateException if no view resolver knows the view, or the view cannot be rendered.
     */
    public ResponseEntity<String> render(final String viewName, final Map<String, ?> model) {
        final var locale = RequestContextUtils.getLocale(request);
        final var view = resolve(viewName, locale);
        final var attributes = new LinkedHashMap<String, Object>(model);
        attributes.put(BrandingProvider.MODEL_ATTRIBUTE, brandingProvider.branding());
        final var capture = new ContentCachingResponseWrapper(response);
        try {
            view.render(attributes, request, capture);
        } catch (final Exception e) {
            throw new IllegalStateException("The page " + viewName + " cannot be rendered", e);
        }
        final var html = new String(capture.getContentAsByteArray(), Charset.forName(capture.getCharacterEncoding()));
        return ResponseEntity.ok().contentType(TEXT_HTML_UTF8).body(html);
    }

Calls to another service are contract first too: the BFF reaches the resource server through a client generated from the resource server’s own contract, behind a domain port (see Documents API). Only endpoints owned by frameworks have no contract here: the Spring Security filters, the Spring Authorization Server protocol endpoints, Spring Boot’s error controller and actuator.

Two tests keep it that way. OpenApiDriftIT, in each boot module, fails when the running application serves an operation, status code or schema its contract does not declare (the pages of auth-server are compared through their own springdoc group, /v3/api-docs/pages). HexagonalArchitectureTest fails when a hand-written class or method carries @RequestMapping or one of its variants, or when a @Controller does not implement a generated interface. apis/README.md describes the layout, the generator options and how to version a contract.

test-support (shared Testcontainers base), e2e-tests (Playwright) and coverage (JaCoCo aggregate) are root modules outside the applications.

Security filter chains

auth-server defines three SecurityFilterChain beans (module auth-server/api/web). ApiSecurityConfig (order 0) secures /api/ statelessly: it validates bearer JWTs issued by this server itself for the API audience, with a decoder of its own (see Tokens and signing keys), leaves registration, e-mail verification and password reset public (rate limited), and requires the scope admin under /api/admin/. In SecurityConfig, the first chain (order 1) applies only to the authorization server protocol endpoints; the second (order 2) secures everything else, including the login page.

    /**
     * Creates the chain of the OAuth 2.1 and OpenID Connect protocol endpoints.
     *
     * @param http        security builder.
     * @param customizers protocol customizers, applied in order.
     * @return the protocol filter chain.
     * @throws Exception if the chain cannot be built.
     */
    @Bean
    @Order(1)
    public SecurityFilterChain authorizationServerSecurityFilterChain(
            final HttpSecurity http, final ObjectProvider<ProtocolChainCustomizer> customizers) throws Exception {
        http
                .oauth2AuthorizationServer(server -> {
                    http.securityMatcher(server.getEndpointsMatcher());
                    server.oidc(Customizer.withDefaults());
                    customizers.orderedStream().forEach(customizer -> customizer.customize(server));
                })
                .authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated())
                .exceptionHandling(exceptions -> exceptions
                        .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint(LOGIN_PATH)));
        return http.build();
    }

    /**
     * Creates the chain of the login page and the rest of the user interface.
     *
     * @param http        security builder.
     * @param customizers login method customizers, applied in order.
     * @return the login/UI filter chain.
     * @throws Exception if the chain cannot be built.
     */
    @Bean
    @Order(2)
    public SecurityFilterChain loginSecurityFilterChain(
            final HttpSecurity http, final ObjectProvider<LoginChainCustomizer> customizers) throws Exception {
        http.formLogin(form -> form.loginPage(LOGIN_PATH).permitAll());
        // customizers run before the catch-all rule below, so they can still permit their own endpoints
        for (final var customizer : customizers.orderedStream().toList()) {
            customizer.customize(http);
        }
        http.authorizeHttpRequests(authorize -> authorize
                .requestMatchers(LOGIN_PATH, "/error", "/actuator/health/**", "/v3/api-docs/**").permitAll()
                .anyRequest().authenticated());
        return http.build();
    }
    /**
     * Creates the chain of the REST API.
     *
     * @param http      security builder.
     * @param jwkSource the published keys of this server.
     * @param issuer    issuer of this server ({@code spring.security.oauth2.authorizationserver.issuer}).
     * @param audience  audience the API requires ({@code authserver.api.audience}).
     * @return the API filter chain.
     * @throws Exception if the chain cannot be built.
     */
    @Bean
    @Order(0)
    public SecurityFilterChain apiSecurityFilterChain(
            final HttpSecurity http, final JWKSource<SecurityContext> jwkSource,
            @Value("${spring.security.oauth2.authorizationserver.issuer}") final String issuer,
            @Value("${" + API_AUDIENCE_PROPERTY + ":" + DefaultClientDefinitions.DEFAULT_API_AUDIENCE + "}")
            final String audience) throws Exception {
        http
                .securityMatcher(API_PATTERN)
                .csrf(AbstractHttpConfigurer::disable)
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers(HttpMethod.POST, "/api/account/register", "/api/account/password/reset",
                                "/api/account/password/reset-request")
                        .permitAll()
                        .requestMatchers(HttpMethod.GET, "/api/account/verify").permitAll()
                        .requestMatchers(ADMIN_PATTERN).hasAuthority(ADMIN_SCOPE_AUTHORITY)
                        .anyRequest().authenticated())
                .oauth2ResourceServer(resource -> resource
                        .jwt(jwt -> jwt.decoder(apiJwtDecoder(jwkSource, issuer, audience))
                                .jwtAuthenticationConverter(apiJwtAuthenticationConverter())));
        return http.build();
    }

    /**
     * Creates the decoder of the API's bearer tokens: signature against the published keys, issuer, timestamps,
     * audience, and no {@code purpose} claim.
     *
     * @param jwkSource the published keys of this server.
     * @param issuer    issuer every token must have.
     * @param audience  audience every token must list.
     * @return the decoder.
     */
    static JwtDecoder apiJwtDecoder(final JWKSource<SecurityContext> jwkSource, final String issuer,
                                    final String audience) {
        final var decoder = NimbusJwtDecoder.withJwkSource(jwkSource).jwsAlgorithm(SignatureAlgorithm.RS256).build();
        decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(List.<OAuth2TokenValidator<Jwt>>of(
                JwtValidators.createDefaultWithIssuer(issuer),
                new JwtClaimValidator<List<String>>(JwtClaimNames.AUD,
                        audiences -> audiences != null && audiences.contains(audience)),
                ApiSecurityConfig::rejectPurposeBoundToken)));
        return decoder;
    }

    /**
     * Rejects a purpose-bound account token (such as an e-mail verification JWT): it is signed by this server but
     * never meant as a bearer token.
     *
     * @param jwt the token.
     * @return a failure when the token carries the {@code purpose} claim, a success otherwise.
     */
    private static OAuth2TokenValidatorResult rejectPurposeBoundToken(final Jwt jwt) {
        if (jwt.hasClaim(SignedTokenService.PURPOSE_CLAIM)) {
            return OAuth2TokenValidatorResult.failure(new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN,
                    "A purpose-bound account token is not a bearer token", null));
        }
        return OAuth2TokenValidatorResult.success();
    }

    /**
     * Creates the converter that maps the {@code scope} claim to {@code SCOPE_*} authorities and the {@code roles}
     * claim to {@code ROLE_*} authorities.
     *
     * @return the converter.
     */
    JwtAuthenticationConverter apiJwtAuthenticationConverter() {
        final var scopes = new JwtGrantedAuthoritiesConverter();
        final var converter = new JwtAuthenticationConverter();
        converter.setJwtGrantedAuthoritiesConverter(jwt -> {
            final var authorities = new ArrayList<GrantedAuthority>(scopes.convert(jwt));
            authorities.addAll(roleAuthorities(jwt));
            return authorities;
        });
        return converter;
    }

Extension points for authentication methods

A feature spans the layers with the same package name in each (…​domain.password, …​application.password, …​infrastructure.persistence.password, …​api.web.password), so authentication methods can be developed in parallel. These extension points avoid editing shared files:

  • LoginChainCustomizer (package api.web.login) is a functional interface over HttpSecurity (deliberately not a Customizer<HttpSecurity>, which Spring Security would apply to every chain). Every bean of this type is applied to the login chain in @Order order, before its catch-all rule.

  • LoginMethodFragment contributes a Thymeleaf fragment to the login page (templates/login.html); the username and password form is the fragment in templates/password.html. See Login pages and the BFF.

  • ProtocolChainCustomizer (package api.web) is the same idea for the protocol endpoints: every bean receives the OAuth2AuthorizationServerConfigurer of the protocol chain, in @Order order. It is how the UserInfo mapper and the optional dynamic client registration are configured. It is also deliberately not a Customizer, which Spring Security would apply to every chain.

  • JwtClaimsContributor (package api.web.tokens) adds claims to issued tokens: access tokens of both formats and ID tokens; see Tokens and signing keys.

<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>

Users and clients

The use case FindUserAccountUseCase (module application) looks a user up through the UserAccountRepository port. The infrastructure/persistence adapter implements it with JDBC, and UserAccountUserDetailsService in api/web adapts the result to Spring Security.

    /** Columns selected for an account. */
    private static final String SELECT_USER = """
            SELECT u.id, u.username, u.enabled, u.email, u.email_verified, u.tenant, p.encoded_password
            FROM users u JOIN user_passwords p ON p.user_id = u.id
            """;

    /** Query returning the user and its encoded password by username. */
    private static final String FIND_USER = SELECT_USER + "WHERE u.username = ?";
    /** Query returning the authorities of a user by user id. */
    private static final String FIND_AUTHORITIES = """
            SELECT authority
            FROM user_authorities
            WHERE user_id = ?
            ORDER BY authority
            """;
    @Override
    public Optional<UserAccount> findByUsername(final String username) {
        return findOne(FIND_USER, username);
    }
    /**
     * Loads one account, with its authorities.
     *
     * @param sql   query selecting the user row by one parameter.
     * @param value value of the parameter.
     * @return the account, or an empty optional when no row matches.
     */
    private Optional<UserAccount> findOne(final String sql, final Object value) {
        return jdbcClient.sql(sql).param(value)
                .query(userAccountRowMapper)
                .optional()
                .map(row -> row.toUserAccount(
                        jdbcClient.sql(FIND_AUTHORITIES).param(row.id()).query(String.class).list()));
    }

Registered clients, authorizations and consents use the JDBC services of Spring Authorization Server.

    /**
     * Creates the repository of registered clients.
     *
     * @param jdbcTemplate JDBC template of the application datasource.
     * @return the registered client repository.
     */
    @Bean
    public RegisteredClientRepository registeredClientRepository(final JdbcTemplate jdbcTemplate) {
        return new JdbcRegisteredClientRepository(jdbcTemplate);
    }

    /**
     * Creates the service that stores OAuth 2 authorizations, decorated to detect the reuse of rotated refresh
     * tokens.
     *
     * @param jdbcTemplate             JDBC template of the application datasource.
     * @param registeredClientRepository repository used to resolve the client of each authorization.
     * @param jsonMapperFactory        creates the mapper that serializes the stored attributes and claims.
     * @return the authorization service.
     */
    @Bean
    public OAuth2AuthorizationService authorizationService(
            final JdbcTemplate jdbcTemplate, final RegisteredClientRepository registeredClientRepository,
            final AuthorizationJsonMapperFactory jsonMapperFactory) {
        final var jsonMapper = jsonMapperFactory.create();
        final var service = new JdbcOAuth2AuthorizationService(jdbcTemplate, registeredClientRepository);
        service.setAuthorizationRowMapper(
                new JdbcOAuth2AuthorizationService.JsonMapperOAuth2AuthorizationRowMapper(
                        registeredClientRepository, jsonMapper));
        service.setAuthorizationParametersMapper(
                new JdbcOAuth2AuthorizationService.JsonMapperOAuth2AuthorizationParametersMapper(jsonMapper));
        return new ReuseDetectingAuthorizationService(service, JdbcClient.create(jdbcTemplate));
    }

    /**
     * Creates the service that stores the consents granted by users.
     *
     * @param jdbcTemplate             JDBC template of the application datasource.
     * @param registeredClientRepository repository used to resolve the client of each consent.
     * @return the authorization consent service.
     */
    @Bean
    public OAuth2AuthorizationConsentService authorizationConsentService(
            final JdbcTemplate jdbcTemplate, final RegisteredClientRepository registeredClientRepository) {
        return new JdbcOAuth2AuthorizationConsentService(jdbcTemplate, registeredClientRepository);
    }

Passwords, accounts, signing keys, tokens and registered clients are described in Passwords and accounts, Tokens and signing keys and Registered clients. The infrastructure/mail adapter implements the AccountMailer port with Spring’s JavaMailSender; its settings live under authserver.mail (sender, base URL for the links, locale).

@ConfigurationProperties(prefix = "authserver.mail")
public record MailProperties(String from, String baseUrl, Locale locale) {

    /** Sender used when none is configured. */
    public static final String DEFAULT_FROM = "no-reply@localhost";

    /** Base URL used when none is configured. */
    public static final String DEFAULT_BASE_URL = "http://localhost:9000";

    /**
     * Applies the defaults of the missing values and removes a trailing slash of the base URL.
     *
     * @param from sender address, or {@code null} for {@link #DEFAULT_FROM}.
     * @param baseUrl public base URL, or {@code null} for {@link #DEFAULT_BASE_URL}.
     * @param locale language of the messages, or {@code null} for English.
     */
    public MailProperties {
        from = from == null || from.isBlank() ? DEFAULT_FROM : from;
        final var url = baseUrl == null || baseUrl.isBlank() ? DEFAULT_BASE_URL : baseUrl;
        baseUrl = url.endsWith("/") ? url.substring(0, url.length() - 1) : url;
        locale = locale == null ? Locale.ENGLISH : locale;
    }
}

BFF and resource server

The bff is an oauth2Login() client using the authorization code grant with PKCE. It keeps the user’s tokens in a server-side session (Spring Session JDBC, cookie __Host-SESSION), protects state-changing requests with CSRF (XSRF-TOKEN cookie, X-XSRF-TOKEN header or _csrf form parameter), serves the SPA, exposes GET /bff/user and GET /bff/login, lets Spring Security’s logout filter answer POST /bff/logout with a redirect to the RP-initiated logout of the authorization server, and serves the documents API (GET /api/documents, DELETE /api/documents/{id}), whose use cases call the resource server with the access token of the user through a generated client. It is described in Login pages and the BFF.

    /**
     * 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();
    }
    /**
     * Returns the subject of the authenticated user. The security chain answers 401 before reaching this method when
     * nobody is signed in, so the principal of the security context is always the OIDC user of the session.
     *
     * @return the signed-in user's subject.
     * @throws AuthenticationCredentialsNotFoundException if no OIDC user is signed in, answered 401 by the chain.
     */
    @Override
    public ResponseEntity<SessionUserResponse> getSessionUser() {
        final var authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !(authentication.getPrincipal() instanceof final OidcUser user)) {
            throw new AuthenticationCredentialsNotFoundException("No OpenID Connect user is signed in");
        }
        return ResponseEntity.ok(sessionUserDtoMapper.toResponse(user));
    }

The resource-server validates JWT access tokens against the issuer and accepts only those whose aud claim lists one of the configured audiences (resource-server by default). Its API and security are described in Resource server.