Resource server

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

The resource-server (port 8081) is hexagonal like auth-server: a Document (id, title, owner) in domain, a list and a delete use case in application, an in-memory repository in infrastructure/memory (a real adapter that needs no schema) and the REST API in api/web.

Documents API

Endpoint Required authority Behavior

GET /api/documents

SCOPE_documents.read

Lists the caller’s documents; an administrator (ROLE_ADMIN) sees all of them. Enforced by the filter chain.

DELETE /api/documents/{id}

SCOPE_documents.delete

Deletes one of the caller’s documents; an administrator (ROLE_ADMIN) may delete any. 204 when deleted, 404 when it does not exist or belongs to someone else. The scope is enforced by method security, the ownership by DeleteDocumentUseCase.

Answering someone else’s document with 404 rather than 403 is deliberate: the answer is then the same as for an identifier that does not exist, so a caller cannot find out which documents exist.

    /**
     * Deletes a document when the caller owns it or is an administrator.
     *
     * @param id            identifier of the document.
     * @param caller        subject of the caller.
     * @param administrator whether the caller is an administrator, who may delete any document.
     * @return {@code true} when the document was deleted, {@code false} when it does not exist or the caller may not
     *         delete it (the two are deliberately indistinguishable).
     */
    public boolean execute(final String id, final String caller, final boolean administrator) {
        // Extension point (#4): the authentication-method check (the `amr` claim of the token, for example to require
        // a multi-factor login) attaches here, before the deletion, as a step-up requirement.
        final var allowed = documentRepository.findById(id)
                .filter(document -> administrator || document.owner().equals(caller))
                .isPresent();
        return allowed && documentRepository.deleteById(id);
    }
    /**
     * Lists the documents of the caller; an administrator ({@code ROLE_ADMIN}) sees every document.
     *
     * @return the documents.
     */
    @Override
    public ResponseEntity<List<DocumentResponse>> listDocuments() {
        final var authentication = caller();
        final var documents = BearerAuthorities.isAdministrator(authentication)
                ? listDocumentsUseCase.listAll()
                : listDocumentsUseCase.listOwn(authentication.getName());
        return ResponseEntity.ok(documentDtoMapper.toResponses(documents));
    }
    /**
     * Deletes a document of the caller; an administrator ({@code ROLE_ADMIN}) may delete any document. Someone
     * else's document is answered like a missing one, so the answer never reveals that it exists.
     *
     * @param id identifier of the document.
     * @return 204 when the document was deleted, 404 when it does not exist or belongs to someone else.
     */
    @Override
    @PreAuthorize("hasAuthority('SCOPE_documents.delete')")
    public ResponseEntity<Void> deleteDocument(final String id) {
        final var authentication = caller();
        return deleteDocumentUseCase.execute(id, authentication.getName(),
                BearerAuthorities.isAdministrator(authentication))
                ? ResponseEntity.noContent().build()
                : ResponseEntity.notFound().build();
    }

The API is defined by the contract apis/resource-server/rest-server/resource-server-api-v1.yaml: DocumentController implements the DocumentsApi interface generated from it, and DocumentDtoMapper maps the domain documents onto the generated DocumentResponse. The running server publishes the matching OpenAPI document at /v3/api-docs, which OpenApiDriftIT compares with the contract; the Swagger UI is not shipped.

  /api/documents:
    get:
      tags: [ documents ]
      operationId: listDocuments
      summary: Lists documents
      description: Lists the caller's documents; an administrator sees all. Needs scope documents.read.
      security:
        - bearer: [ documents.read ]
      responses:
        '200':
          description: The documents.
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/DocumentResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: The token lacks the documents.read scope.
          headers:
            WWW-Authenticate:
              $ref: '#/components/headers/WwwAuthenticate'
  /api/documents/{id}:
    delete:
      tags: [ documents ]
      operationId: deleteDocument
      summary: Deletes a document
      description: >-
        Deletes one of the caller's documents; an administrator may delete any. Needs scope documents.delete and a
        recent strong authentication (RFC 9470). Someone else's document is answered 404, like a missing one.
      security:
        - bearer: [ documents.delete ]
      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: >-
            Missing or invalid bearer token, or (RFC 9470) a valid token that does not prove a recent enough strong
            authentication: its acr claim is not the required one or its auth_time is older than the maximum age.
            The client must send the user through the authorization server again, asking for the acr_values and
            max_age of the challenge.
          headers:
            WWW-Authenticate:
              description: >-
                RFC 6750 bearer challenge. When step-up authentication is required it is
                Bearer error="insufficient_user_authentication", acr_values="urn:irurueta:acr:mfa", max_age="300"
                (the values configured under resourceserver.step-up.*).
              schema:
                type: string
        '403':
          description: The token lacks the documents.delete scope.
          headers:
            WWW-Authenticate:
              $ref: '#/components/headers/WwwAuthenticate'
        '404':
          description: The document does not exist or belongs to someone else.

Token validation

By default tokens are JWTs. The decoder is built from spring.security.oauth2.resourceserver.jwt.issuer-uri (AUTH_ISSUER) and only accepts tokens whose aud claim lists one of spring.security.oauth2.resourceserver.jwt.audiences (RESOURCE_SERVER_AUDIENCES, default resource-server). The application refuses to start when that list is empty, instead of accepting every token. Failures answer with the RFC 6750 WWW-Authenticate challenge (invalid_token or insufficient_scope).

    /**
     * Builds the filter chain validating bearer JWTs (the decoder is built from {@code issuer-uri}, and the
     * configured audiences are validated by it).
     *
     * @param http       the HTTP security builder.
     * @param properties the resource server properties.
     * @param stepUp     requires a recent strong authentication to delete.
     * @param accessDeniedHandler answers the denials, including the step-up challenge.
     * @return the security filter chain.
     * @throws Exception if the chain cannot be built.
     * @throws IllegalStateException if no accepted audience is configured.
     */
    @Bean
    @Profile("!opaque")
    SecurityFilterChain resourceServerFilterChain(final HttpSecurity http,
            final OAuth2ResourceServerProperties properties, final StepUpAuthorizationManager stepUp,
            final StepUpAccessDeniedHandler accessDeniedHandler) throws Exception {
        requireAudiences(properties.getJwt().getAudiences());
        authorize(http, stepUp);
        http.oauth2ResourceServer(oauth2 -> oauth2
                .jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter()))
                // DPoP (RFC 9449): "Authorization: DPoP <token>" plus a proof; the framework already refuses a
                // token whose cnf holds jkt when it arrives as Bearer. A cnf.x5t#S256 token is checked against the
                // TLS client certificate by the validator of the decoder Boot builds (no JwtDecoder bean here).
                .dPoP(Customizer.withDefaults())
                .authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint())
                .accessDeniedHandler(accessDeniedHandler));
        return http.build();
    }

The converter maps the scope claim to SCOPE_* authorities and the roles claim to ROLE_* authorities.

    /**
     * Maps the {@code scope} claim to {@code SCOPE_*} authorities (the default converter) and the {@code roles}
     * claim to {@code ROLE_*} authorities.
     *
     * @return the converter.
     */
    JwtAuthenticationConverter jwtAuthenticationConverter() {
        final var scopes = new JwtGrantedAuthoritiesConverter();
        final var converter = new JwtAuthenticationConverter();
        converter.setJwtGrantedAuthoritiesConverter(jwt -> {
            final var authorities = new ArrayList<GrantedAuthority>(scopes.convert(jwt));
            authorities.addAll(BearerAuthorities.roleAuthorities(
                    jwt.getClaimAsStringList(BearerAuthorities.ROLES_CLAIM)));
            return authorities;
        });
        return converter;
    }

Certificate-bound and DPoP-bound tokens

The JWT chain accepts DPoP (Authorization: DPoP). A token with cnf.x5t#S256 is accepted only on a TLS connection presenting the same certificate (Spring’s validator, already in Boot’s decoder, reads the request’s client certificate; set server.ssl.client-auth: want and a bundle), and a token with cnf.jkt is refused as a Bearer token or without a valid proof. The DPoP replay cache is per instance and the htu check needs the request URL unchanged by any proxy. See Client credentials and service-to-service calls.

                // DPoP (RFC 9449): "Authorization: DPoP <token>" plus a proof; the framework already refuses a
                // token whose cnf holds jkt when it arrives as Bearer. A cnf.x5t#S256 token is checked against the
                // TLS client certificate by the validator of the decoder Boot builds (no JwtDecoder bean here).
                .dPoP(Customizer.withDefaults())

Step-up authentication (RFC 9470)

Deleting a document needs a recent multi-factor sign-in. StepUpAuthorizationManager checks that the token’s acr claim is one of the configured values (acr-values is a space-separated list, like the acr_values parameter) and that auth_time is no older than max-age; otherwise StepUpAccessDeniedHandler answers 401 with WWW-Authenticate: Bearer error="insufficient_user_authentication" and the acr_values and max_age the client must request (see Multi-factor authentication and step-up). The policy is bound from resourceserver.step-up.*: enabled (default true), acr-values (default urn:irurueta:acr:mfa) and max-age (default PT5M).

@ConfigurationProperties("resourceserver.step-up")
public record StepUpProperties(
        @DefaultValue("true") boolean enabled,
        @DefaultValue("urn:irurueta:acr:mfa") String acrValues,
        @DefaultValue("PT5M") Duration maxAge) {

    /**
     * Validates the policy.
     *
     * @throws IllegalArgumentException if {@code acrValues} is blank or {@code maxAge} is not positive.
     */
    public StepUpProperties {
        if (!StringUtils.hasText(acrValues)) {
            throw new IllegalArgumentException("resourceserver.step-up.acr-values must not be blank");
        }
        if (maxAge == null || maxAge.isNegative() || maxAge.isZero()) {
            throw new IllegalArgumentException("resourceserver.step-up.max-age must be positive");
        }
    }
}
@RequiredArgsConstructor
public class StepUpAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {

    /** Claim carrying the authentication context class reference. */
    static final String ACR_CLAIM = "acr";

    /** Claim carrying the time of the user's authentication, in epoch seconds. */
    static final String AUTH_TIME_CLAIM = "auth_time";

    /** Separator of the configured {@code acr-values}: any run of whitespace. */
    private static final String ACR_VALUES_SEPARATOR = "\\s+";

    /** Authority the caller needs before the step-up requirement is evaluated. */
    private final String requiredAuthority;

    /** Step-up policy. */
    private final StepUpProperties properties;

    /** Source of the current time. */
    private final Clock clock;

    @Override
    public AuthorizationResult authorize(final Supplier<? extends Authentication> authentication,
            final RequestAuthorizationContext context) {
        final var current = authentication.get();
        if (current == null || !current.isAuthenticated() || current.getAuthorities().stream()
                .noneMatch(authority -> requiredAuthority.equals(authority.getAuthority()))) {
            return new AuthorizationDecision(false);
        }
        if (!properties.enabled() || satisfied(current)) {
            return new AuthorizationDecision(true);
        }
        return new StepUpRequiredDecision();
    }

    /**
     * Tells whether the token proves the required authentication.
     *
     * @param authentication the authenticated bearer token.
     * @return {@code true} when the {@code acr} matches and {@code auth_time} is recent enough.
     */
    private boolean satisfied(final Authentication authentication) {
        if (!(authentication instanceof AbstractOAuth2TokenAuthenticationToken<?> token)) {
            return false;
        }
        final var attributes = token.getTokenAttributes();
        if (!isAccepted(attributes.get(ACR_CLAIM))) {
            return false;
        }
        final var authenticatedAt = toInstant(attributes.get(AUTH_TIME_CLAIM));
        return authenticatedAt != null
                && !authenticatedAt.plus(properties.maxAge()).isBefore(clock.instant());
    }

    /**
     * Tells whether an {@code acr} value is one of the configured ones. The configured {@code acr-values} is a
     * space-separated list, like the {@code acr_values} parameter of OpenID Connect, so the token's single value must
     * be a member of it, never equal to the whole list.
     *
     * @param acr the {@code acr} claim of the token.
     * @return {@code true} when the claim is a text listed in the configured values.
     */
    private boolean isAccepted(final Object acr) {
        return acr instanceof String value
                && Arrays.asList(properties.acrValues().trim().split(ACR_VALUES_SEPARATOR)).contains(value);
    }

    /**
     * Converts an {@code auth_time} value, which is epoch seconds in a JWT or an introspection answer.
     *
     * @param value the claim value.
     * @return the instant, or {@code null} when the value is missing or of an unexpected type.
     */
    private static Instant toInstant(final Object value) {
        return switch (value) {
            case Instant instant -> instant;
            case Number number -> Instant.ofEpochSecond(number.longValue());
            case null, default -> null;
        };
    }
}
@RequiredArgsConstructor
public class StepUpAccessDeniedHandler implements AccessDeniedHandler {

    /** Handler of every denial that is not a step-up requirement. */
    private final AccessDeniedHandler delegate;

    /** Step-up policy, whose values are advertised in the challenge. */
    private final StepUpProperties properties;

    @Override
    public void handle(final HttpServletRequest request, final HttpServletResponse response,
            final AccessDeniedException accessDeniedException) throws IOException, ServletException {
        if (accessDeniedException instanceof AuthorizationDeniedException denied
                && denied.getAuthorizationResult() instanceof StepUpRequiredDecision) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Bearer error=\"insufficient_user_authentication\", "
                    + "acr_values=\"" + properties.acrValues() + "\", max_age=\""
                    + properties.maxAge().toSeconds() + "\"");
            return;
        }
        delegate.handle(request, response, accessDeniedException);
    }
}
    /**
     * Builds the manager that requires a recent strong authentication to delete a document.
     *
     * @param properties the step-up policy.
     * @return the manager.
     */
    @Bean
    StepUpAuthorizationManager stepUpAuthorizationManager(final StepUpProperties properties) {
        return new StepUpAuthorizationManager(DELETE_AUTHORITY, properties, Clock.systemUTC());
    }

    /**
     * Builds the handler that answers the step-up requirement with the RFC 9470 challenge and every other denial
     * with the RFC 6750 one.
     *
     * @param properties the step-up policy.
     * @return the handler.
     */
    @Bean
    StepUpAccessDeniedHandler stepUpAccessDeniedHandler(final StepUpProperties properties) {
        return new StepUpAccessDeniedHandler(new BearerTokenAccessDeniedHandler(), properties);
    }

Opaque token profile

With the Spring profile opaque, the resource server introspects tokens instead. The introspection URI and client credentials come from the environment variables AUTH_INTROSPECTION_URI, INTROSPECTION_CLIENT_ID and INTROSPECTION_CLIENT_SECRET, with no defaults. AudienceRolesOpaqueTokenIntrospector applies the same audience check and role mapping, so both variants behave alike.

The resource server authenticates to the introspection endpoint as a client of its own, which must be registered first, for example through POST /api/admin/clients: a confidential client (say resource-server) with the client_secret_basic method and no redirect URI (any confidential client may call the introspection endpoint; the client_credentials grant is a convenient choice but not required); its generated secret goes into INTROSPECTION_CLIENT_SECRET, never into a file. The tokens it validates are the reference access tokens ("accessTokenFormat": "reference") of clients whose audiences list resource-server: the authorization server stores their roles, tenant and aud with the authorization (see Tokens and signing keys), and the introspection answer carries them. The end-to-end test ResourceServerEndToEndIT runs this profile against the real authorization server.