Tokens and signing keys

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

Persisted, rotating signing keys

Signing keys are RSA keys (RS256) stored in the signing_keys table with a status of NEXT, ACTIVE or RETIRED. The private half is encrypted with AES-256-GCM (Encryptors.stronger) using a password and salt from authserver.keys.encryption.password and authserver.keys.encryption.salt, which come from the environment in production and are never committed. With the dev profile, a random secret is created once under ~/.irurueta-auth-server/ (readable by the owner only) and reused, so persisted keys survive restarts.

/**
 * Inputs of the encryption of private signing keys at rest.
 *
 * <p>The record never prints its values: a log line or an exception message that mentions it cannot leak them.
 *
 * @param password the passphrase the encryption key is derived from.
 * @param salt     the salt of the derivation, hex encoded.
 */
public record KeyEncryptionProperties(String password, String salt) {

    /**
     * Validates the properties.
     *
     * @throws IllegalArgumentException if the passphrase or the salt is null or blank.
     */
    public KeyEncryptionProperties {
        if (password == null || password.isBlank() || salt == null || salt.isBlank()) {
            throw new IllegalArgumentException("authserver.keys.encryption.password and .salt must be set");
        }
    }

    /**
     * Describes the properties without revealing them.
     *
     * @return a fixed text.
     */
    @Override
    public String toString() {
        return "KeyEncryptionProperties[redacted]";
    }
}
CREATE TABLE signing_keys
(
    kid                   varchar(64)              NOT NULL,
    alg                   varchar(20)              NOT NULL,
    public_jwk            text                     NOT NULL,
    private_jwk_encrypted text                     NOT NULL,
    status                varchar(20)              NOT NULL,
    created_at            timestamp with time zone NOT NULL,
    activated_at          timestamp with time zone,
    retired_at            timestamp with time zone,
    PRIMARY KEY (kid),
    CONSTRAINT ck_signing_keys_status CHECK (status IN ('NEXT', 'ACTIVE', 'RETIRED'))
);

-- At most one key can sign at any time.
CREATE UNIQUE INDEX uq_signing_keys_single_active ON signing_keys (status) WHERE status = 'ACTIVE';

RotateSigningKeysUseCase applies the lifecycle: it creates the ACTIVE and NEXT keys when missing, promotes NEXT and retires the old ACTIVE key when the rotation interval has elapsed, always leaves a fresh NEXT key, and deletes keys retired for longer than the retention. The start-up runner and SigningKeyRotationJob call execute(), which only rotates a key that is due; POST /api/admin/keys/rotate calls executeForced(), which retires the active key now whatever its age (for example after a suspected compromise). Rotation runs in one transaction guarded by a PostgreSQL advisory lock, so two instances never rotate at once.

    /**
     * Does whatever the key lifecycle requires at the current instant: the scheduled path, which only rotates a key
     * that has signed for the whole rotation interval.
     */
    public void execute() {
        run(false);
    }

    /**
     * Rotates now, whatever the age of the active key: the active key is retired, the next key promoted and a new
     * next key generated (for example after a suspected key compromise). Expired retired keys are deleted too.
     */
    public void executeForced() {
        run(true);
    }

    /**
     * Applies the lifecycle transitions while holding the rotation lock.
     *
     * @param force whether the active key is replaced even when it is not due.
     */
    private void run(final boolean force) {
        final var now = clock.instant();
        final var retention = signingKeyRetention.effective();
        signingKeyRepository.withRotationLock(() -> {
            rotate(now, force, retention);
            return null;
        });
    }

    /**
     * Applies the lifecycle transitions that are due, or forced.
     *
     * @param now       current instant.
     * @param force     whether the active key is replaced even when it is not due.
     * @param retention how long a retired key stays published.
     */
    private void rotate(final Instant now, final boolean force, final Duration retention) {
        final var keys = signingKeyRepository.findAll();
        var active = first(keys, SigningKeyStatus.ACTIVE);
        var next = first(keys, SigningKeyStatus.NEXT);
        if (active != null && (force || isDue(active, now))) {
            signingKeyRepository.save(active.retire(now));
            active = null;
        }
        if (active == null) {
            final var promoted = next != null ? next : signingKeyGenerator.generate(now);
            signingKeyRepository.save(promoted.activate(now));
            next = null;
        }
        if (next == null) {
            signingKeyRepository.save(signingKeyGenerator.generate(now));
        }
        keys.stream()
                .filter(key -> key.status() == SigningKeyStatus.RETIRED && isExpired(key, now, retention))
                .forEach(key -> signingKeyRepository.deleteByKid(key.kid()));
    }
    @Override
    public <T> T withRotationLock(final Supplier<T> action) {
        return transactionTemplate.execute(status -> {
            // the lock is released when the transaction ends; the row mapper only drains the (void) result
            jdbcClient.sql("SELECT pg_advisory_xact_lock(?)").param(ROTATION_LOCK_KEY)
                    .query((rs, rowNum) -> Boolean.TRUE).list();
            return action.get();
        });
    }

A retired key must stay published for as long as any token it signed can still be presented. SigningKeyRetention therefore computes the effective retention as the longest of the configured retention and the longest signed-token lifetime plus the clock skew. The signed tokens are the access tokens of the clients with self-contained tokens and the ID tokens (reported by the SignedTokenLifetimes port, implemented over the registered clients by RegisteredClientTokenLifetimes; Spring Authorization Server fixes the ID-token lifetime at 30 minutes) and the 24-hour e-mail verification tokens. Registering a client with longer-lived tokens lengthens it automatically.

    /**
     * Computes the effective retention at this moment: registering a client with longer-lived tokens lengthens it.
     *
     * @return the longest of the configured retention and the longest signed-token lifetime plus the clock skew.
     */
    public Duration effective() {
        final var longestToken = Stream.of(signedTokenLifetimes.longest(), RegisterAccountUseCase.VERIFICATION_TTL)
                .max(Duration::compareTo).orElseThrow();
        final var needed = longestToken.plus(clockSkew);
        return needed.compareTo(configuredRetention) > 0 ? needed : configuredRetention;
    }
Property Default Meaning

authserver.keys.rotation-interval

P30D

How long a key signs before it is replaced.

authserver.keys.retention

PT2H

Minimum time a retired key stays published; the effective retention is never shorter than the longest signed-token lifetime plus the clock skew.

authserver.keys.clock-skew

PT60S

Clock skew the token consumers tolerate, added to the longest signed-token lifetime.

authserver.keys.rotation.cron

0 0 * * * *

Schedule of SigningKeyRotationJob.

authserver.keys.jwks-cache-ttl

PT30S

How long the published key set is cached.

authserver.tokens.cleanup.cron

0 0 * * * *

Schedule of ExpiredAuthorizationCleanupJob, which deletes expired and abandoned authorizations.

authserver.tokens.cleanup.abandoned-after

P1D

Age after which an authorization that never got a token (an authorization or consent request the user abandoned) is deleted.

authserver.account.cleanup.cron

0 30 * * * *

Schedule of ExpiredAccountTokenCleanupJob, which deletes expired account (password reset) tokens.

Scheduling is switched on once, for every feature, by SchedulingConfiguration in the root api.web package.

An expired authorization has every token expiry in the past. An authorization that never got a token has no expiry at all, so a created_at column (migration V240) dates it:

-- When each authorization row was created. Spring Authorization Server lists its columns explicitly, so the default
-- fills it in. An authorization that never got a token (an authorization or consent request the user abandoned) has
-- no expiry at all; the clean-up job deletes it once it is older than a configurable threshold.
ALTER TABLE oauth2_authorization
    ADD COLUMN created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP;

Two beans are built over the same table: the JWKSource publishes active, next and still-valid retired public keys at the JWKS endpoint, while the JwtEncoder signs only with the active key.

/**
 * Serves the signing keys kept by the key use cases. Two views of them exist on purpose: the public JWKS lists the
 * active key, the next key and the still-valid retired keys, whereas the {@link JwtEncoder} only ever sees the single
 * active key with its private half, so signing never has to choose between several keys. The conversion of the
 * stored keys into JSON Web Keys belongs to the {@link SigningKeyJwkMapper}.
 */
@Configuration(proxyBeanMethods = false)
public class DatabaseJwkSourceConfiguration {

    /**
     * Creates the cached set of public keys.
     *
     * @param published use case that finds the keys to publish.
     * @param mapper    maps the keys onto JSON Web Keys.
     * @param clock     source of the current time.
     * @param ttl       how long the set is kept ({@code authserver.keys.jwks-cache-ttl} in {@code application.yml}).
     * @return the cache; call {@link CachedJwkSet#refresh()} after a rotation.
     */
    @Bean
    public CachedJwkSet publishedJwkSet(
            final PublishedSigningKeysUseCase published, final SigningKeyJwkMapper mapper, final Clock clock,
            @Value("${authserver.keys.jwks-cache-ttl}") final Duration ttl) {
        return new CachedJwkSet(() -> mapper.toPublicJwkSet(published.execute()), ttl, clock);
    }

    /**
     * Creates the cached set holding only the active key, with its private half.
     *
     * @param active use case that finds the active key.
     * @param mapper maps the key onto a JSON Web Key, decrypting its private half.
     * @param clock  source of the current time.
     * @param ttl    how long the set is kept ({@code authserver.keys.jwks-cache-ttl} in {@code application.yml}).
     * @return the cache; call {@link CachedJwkSet#refresh()} after a rotation.
     */
    @Bean
    public CachedJwkSet signingJwkSet(
            final ActiveSigningKeyUseCase active, final SigningKeyJwkMapper mapper, final Clock clock,
            @Value("${authserver.keys.jwks-cache-ttl}") final Duration ttl) {
        return new CachedJwkSet(() -> mapper.toSigningJwkSet(active.execute()), ttl, clock);
    }

    /**
     * Creates the source of the public JWKS. It never holds a private key.
     *
     * @param publishedJwkSet the cached public keys.
     * @return the source.
     */
    @Bean
    public JWKSource<SecurityContext> jwkSource(@Qualifier("publishedJwkSet") final CachedJwkSet publishedJwkSet) {
        return (selector, context) -> selector.select(publishedJwkSet.get());
    }

    /**
     * Creates the encoder that signs tokens with the active key.
     *
     * @param signingJwkSet the cached active key.
     * @return the encoder.
     */
    @Bean
    public JwtEncoder jwtEncoder(@Qualifier("signingJwkSet") final CachedJwkSet signingJwkSet) {
        return new NimbusJwtEncoder((selector, context) -> selector.select(signingJwkSet.get()));
    }
}

NimbusSignedTokenService implements the SignedTokenService port with that key and is used for the e-mail verification token.

/**
 * Issues and verifies purpose-bound tokens as JWTs signed with the active signing key and verified against the
 * published keys. Verification checks the signature, the issuer, the timestamps and then the purpose; every failure
 * is reported the same way, as an empty result.
 */
@Component
public class NimbusSignedTokenService implements SignedTokenService {

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

    /** Issuer written to, and required of, every token. */
    private final String issuer;

    /** Signs tokens. */
    private final JwtEncoder encoder;

    /** Verifies tokens. */
    private final JwtDecoder decoder;

    /**
     * Creates the service.
     *
     * @param encoder   signs tokens with the active key.
     * @param jwkSource public keys the signatures are verified against.
     * @param clock     source of the current time.
     * @param issuer    issuer of the tokens ({@code spring.security.oauth2.authorizationserver.issuer}).
     */
    public NimbusSignedTokenService(
            final JwtEncoder encoder, final JWKSource<SecurityContext> jwkSource, final Clock clock,
            @Value("${spring.security.oauth2.authorizationserver.issuer}") final String issuer) {
        this.encoder = encoder;
        this.clock = clock;
        this.issuer = issuer;
        final var timestamps = new JwtTimestampValidator();
        timestamps.setClock(clock);
        final var nimbusDecoder = NimbusJwtDecoder.withJwkSource(jwkSource)
                .jwsAlgorithm(SignatureAlgorithm.RS256)
                .build();
        nimbusDecoder.setJwtValidator(new DelegatingOAuth2TokenValidator<Jwt>(
                List.<OAuth2TokenValidator<Jwt>>of(new JwtIssuerValidator(issuer), timestamps)));
        decoder = nimbusDecoder;
    }

    /**
     * Issues a signed token.
     *
     * @param subject who or what the token is about.
     * @param purpose what the token allows.
     * @param ttl     how long the token stays valid.
     * @return the compact token.
     */
    @Override
    public String issue(final String subject, final String purpose, final Duration ttl) {
        final var now = clock.instant();
        final var claims = JwtClaimsSet.builder()
                .issuer(issuer)
                .subject(subject)
                .issuedAt(now)
                .expiresAt(now.plus(ttl))
                .claim(PURPOSE_CLAIM, purpose)
                .build();
        final var header = JwsHeader.with(SignatureAlgorithm.RS256).build();
        return encoder.encode(JwtEncoderParameters.from(header, claims)).getTokenValue();
    }

    /**
     * Verifies a token.
     *
     * @param token   the compact token.
     * @param purpose purpose the token must have been issued for.
     * @return the subject, or an empty optional when the token is expired, tampered, malformed, from another issuer or
     *         issued for another purpose.
     */
    @Override
    public Optional<String> verify(final String token, final String purpose) {
        try {
            final var jwt = decoder.decode(token);
            if (purpose != null && purpose.equals(jwt.getClaimAsString(PURPOSE_CLAIM))) {
                return Optional.ofNullable(jwt.getSubject());
            }
            return Optional.empty();
        } catch (final JwtException | IllegalArgumentException e) {
            return Optional.empty();
        }
    }
}

Administrators can list the keys (GET /api/admin/keys, never exposing private material) and force a rotation (POST /api/admin/keys/rotate, the forced path above).

Bearer tokens of the API

The /api/ chain (ApiSecurityConfig) has a decoder of its own, separate from the one the UserInfo endpoint uses. It accepts a token only when this server signed it (published keys), its issuer is this server, its timestamps are valid, its aud lists the API audience (authserver.api.audience, default auth-server) and it does not carry the purpose claim of the account tokens, so a user’s access token for the resource server, or an e-mail verification JWT, is answered 401. /api/admin/ needs the admin scope; the ADMIN role alone does not open it. The seeded bff and spa-public clients carry the API audience (so their users can change their password) but never the admin scope.

Token contents

IssuedTokenClaims adds the roles, tenant and aud claims to access tokens, whatever their format. The audience is the logical API identifier configured per client (client setting audiences, default the client id). RolesTenantAudienceTokenCustomizer applies it to the JWTs (access and ID tokens) and ReferenceTokenClaimsCustomizer to the claims stored for a reference (opaque) access token, which the introspection endpoint returns, so a resource server that introspects sees the same claims as one that decodes a JWT. Other features add claims, for example amr or acr, without editing them, by declaring JwtClaimsContributor beans, applied in @Order order to the access tokens of both formats and to the ID tokens (a contributor checks context.getTokenType() when a claim belongs to one kind only). ID tokens get the contributed claims but none of roles, tenant or aud.

/**
 * Extension point that lets a feature add claims to the tokens issued by the authorization server: the access tokens,
 * whether self-contained (JWT) or reference (their claims are returned by the introspection endpoint), and the ID
 * tokens. Every bean of this type is applied by {@link IssuedTokenClaims}, in
 * {@link org.springframework.core.annotation.Order} order, after the built-in claims, so a later contributor may
 * override them. A contributor that only concerns one kind of token checks {@link OAuth2TokenContext#getTokenType()}.
 */
@FunctionalInterface
public interface JwtClaimsContributor {

    /**
     * Adds claims to the token being issued.
     *
     * @param context the token context, with the token type, the principal, the client and the grant type.
     * @param claims  the mutable claims of the token being built.
     */
    void contribute(OAuth2TokenContext context, Map<String, Object> claims);
}
/**
 * The claims this server adds to the tokens it issues, whatever their format, so the self-contained (JWT) access
 * tokens and the reference (opaque) ones carry the same claims: {@link RolesTenantAudienceTokenCustomizer} applies it
 * to the JWTs and {@link ReferenceTokenClaimsCustomizer} to the claims stored for a reference token (which the
 * introspection endpoint returns).
 *
 * <p>An access token gets {@code roles}, {@code tenant} and {@code aud}: the roles are the authorities of the user,
 * the tenant comes from the user account, the audiences from the {@value #AUDIENCES_SETTING} custom setting of the
 * client. Tokens of the client credentials grant have no user, so they get no roles and no tenant. An ID token gets
 * none of them. Then every {@link JwtClaimsContributor}, in order, adds its own claims to the access and ID tokens
 * (it can tell them apart with {@link OAuth2TokenContext#getTokenType()}); no other token is touched.
 */
@Component
@RequiredArgsConstructor
public class IssuedTokenClaims {

    /**
     * Name of the custom client setting that holds the audiences of the access tokens. It is the same name the
     * persistence adapter writes (that module cannot be referenced from here).
     */
    public static final String AUDIENCES_SETTING = "settings.client.audiences";

    /** Name of the claim that holds the roles of the user. */
    public static final String ROLES_CLAIM = "roles";

    /** Name of the claim that holds the tenant of the user. */
    public static final String TENANT_CLAIM = "tenant";

    /** Type of the OpenID Connect ID token. */
    static final OAuth2TokenType ID_TOKEN = new OAuth2TokenType(OidcParameterNames.ID_TOKEN);

    /** Prefix of the authorities that record how a user authenticated, such as {@code FACTOR_PASSWORD}. */
    private static final String FACTOR_PREFIX = "FACTOR_";

    /** Finds the account of the user. */
    private final FindUserAccountUseCase findUserAccountUseCase;

    /** Contributors of additional claims, in order. */
    private final List<JwtClaimsContributor> contributors;

    /**
     * Adds the claims of the token being issued.
     *
     * @param context the token context, with the token type, the principal, the client and the grant type.
     * @param claims  the mutable claims of the token being built.
     */
    public void apply(final OAuth2TokenContext context, final Map<String, Object> claims) {
        if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) {
            addAccessTokenClaims(context, claims);
        } else if (!ID_TOKEN.equals(context.getTokenType())) {
            return;
        }
        contributors.forEach(contributor -> contributor.contribute(context, claims));
    }

    /**
     * Adds the roles, the tenant and the audiences of an access token.
     *
     * @param context the token context.
     * @param claims  the mutable claims of the token being built.
     */
    private void addAccessTokenClaims(final OAuth2TokenContext context, final Map<String, Object> claims) {
        if (context.getAuthorizationGrantType() != null
                && !AuthorizationGrantType.CLIENT_CREDENTIALS.equals(context.getAuthorizationGrantType())) {
            final Authentication principal =
                    Objects.requireNonNull(context.getPrincipal(), "a user grant has a principal");
            // factor authorities (FACTOR_PASSWORD, ...) record how the user signed in; they are not roles. The
            // list is a mutable one on purpose: the authorization store only deserializes allow-listed types, and
            // an immutable list copy (Stream.toList) is not one of them.
            claims.put(ROLES_CLAIM, principal.getAuthorities().stream()
                    .map(GrantedAuthority::getAuthority)
                    .filter(authority -> !authority.startsWith(FACTOR_PREFIX)).sorted()
                    .collect(Collectors.toCollection(ArrayList::new)));
            findUserAccountUseCase.execute(principal.getName())
                    .ifPresent(account -> claims.put(TENANT_CLAIM, account.tenant()));
        }
        if (context.getRegisteredClient().getClientSettings().getSetting(AUDIENCES_SETTING)
                instanceof List<?> audiences && !audiences.isEmpty()) {
            claims.put(OAuth2TokenClaimNames.AUD, audiences.stream().map(String::valueOf)
                    .collect(Collectors.toCollection(ArrayList::new)));
        }
    }
}
/**
 * Adds the claims of {@link IssuedTokenClaims} to the self-contained tokens (JWT access tokens and ID tokens): the
 * {@code roles}, {@code tenant} and {@code aud} claims of an access token, then the claims of every
 * {@link JwtClaimsContributor}, which also reach the ID tokens. It is the one
 * {@code OAuth2TokenCustomizer<JwtEncodingContext>} of the server.
 */
@Component
@RequiredArgsConstructor
public class RolesTenantAudienceTokenCustomizer implements OAuth2TokenCustomizer<JwtEncodingContext> {

    /** The claims every issued token gets. */
    private final IssuedTokenClaims issuedTokenClaims;

    @Override
    public void customize(final JwtEncodingContext context) {
        context.getClaims().claims(claims -> issuedTokenClaims.apply(context, claims));
    }
}
/**
 * Adds the claims of {@link IssuedTokenClaims} to the reference (opaque) access tokens. Such a token carries no
 * claims itself: the claims are stored with the authorization and returned by the introspection endpoint, so a
 * resource server that introspects it sees the same {@code roles}, {@code tenant}, {@code aud} and contributed
 * claims as one that decodes a JWT. It is the one {@code OAuth2TokenCustomizer<OAuth2TokenClaimsContext>} of the
 * server.
 */
@Component
@RequiredArgsConstructor
public class ReferenceTokenClaimsCustomizer implements OAuth2TokenCustomizer<OAuth2TokenClaimsContext> {

    /** The claims every issued token gets. */
    private final IssuedTokenClaims issuedTokenClaims;

    @Override
    public void customize(final OAuth2TokenClaimsContext context) {
        context.getClaims().claims(claims -> issuedTokenClaims.apply(context, claims));
    }
}

UserInfoMapper builds the OpenID Connect UserInfo response and is registered through a ProtocolChainCustomizer.

/**
 * Builds the OpenID Connect UserInfo response from the account of the user, limited to the granted scopes: the
 * {@code sub} claim always; {@code preferred_username}, {@code roles} and {@code tenant} with the {@code profile}
 * scope; {@code email} and {@code email_verified} with the {@code email} scope.
 */
@Component
@RequiredArgsConstructor
public class UserInfoMapper implements Function<OidcUserInfoAuthenticationContext, OidcUserInfo> {

    /** Scope that grants the profile claims. */
    public static final String PROFILE_SCOPE = "profile";

    /** Scope that grants the e-mail claims. */
    public static final String EMAIL_SCOPE = "email";

    /** Finds the account of the user. */
    private final FindUserAccountUseCase findUserAccountUseCase;

    @Override
    public OidcUserInfo apply(final OidcUserInfoAuthenticationContext context) {
        final var username = context.getAuthorization().getPrincipalName();
        final var scopes = context.getAccessToken().getScopes();
        final var claims = new HashMap<String, Object>();
        claims.put(StandardClaimNames.SUB, username);
        findUserAccountUseCase.execute(username).ifPresent(account -> {
            if (scopes.contains(PROFILE_SCOPE)) {
                claims.put(StandardClaimNames.PREFERRED_USERNAME, account.username());
                claims.put(IssuedTokenClaims.ROLES_CLAIM, account.authorities());
                claims.put(IssuedTokenClaims.TENANT_CLAIM, account.tenant());
            }
            if (scopes.contains(EMAIL_SCOPE) && account.email() != null) {
                claims.put(StandardClaimNames.EMAIL, account.email());
                claims.put(StandardClaimNames.EMAIL_VERIFIED, account.emailVerified());
            }
        });
        return new OidcUserInfo(claims);
    }
}
    /**
     * Creates the customizer that installs the UserInfo mapper.
     *
     * @param userInfoMapper mapper that builds the UserInfo response.
     * @return the protocol chain customizer.
     */
    @Bean
    public ProtocolChainCustomizer userInfoProtocolChainCustomizer(final UserInfoMapper userInfoMapper) {
        return server -> server.oidc(oidc -> oidc.userInfoEndpoint(
                endpoint -> endpoint.userInfoMapper(userInfoMapper)));
    }

Refresh token reuse detection

Refresh tokens rotate. A decorator over OAuth2AuthorizationService records the hash of every rotated-out refresh token in consumed_refresh_tokens; presenting one of them revokes the whole authorization, because the token was stolen or replayed.

    @Override
    public void save(final OAuth2Authorization authorization) {
        final var previous = delegate.findById(authorization.getId());
        delegate.save(authorization);
        if (previous == null) {
            return;
        }
        final var oldToken = refreshTokenValue(previous);
        if (oldToken != null && !oldToken.equals(refreshTokenValue(authorization))) {
            jdbcClient.sql(INSERT_CONSUMED).params(hash(oldToken), authorization.getId()).update();
        }
    }

    @Override
    public void remove(final OAuth2Authorization authorization) {
        delegate.remove(authorization);
    }

    @Override
    public OAuth2Authorization findById(final String id) {
        return delegate.findById(id);
    }

    @Override
    public OAuth2Authorization findByToken(final String token, final OAuth2TokenType tokenType) {
        final var authorization = delegate.findByToken(token, tokenType);
        if (authorization != null || (tokenType != null && !OAuth2TokenType.REFRESH_TOKEN.equals(tokenType))) {
            return authorization;
        }
        jdbcClient.sql(FIND_CONSUMED).param(hash(token)).query(String.class).optional()
                .map(delegate::findById)
                .ifPresent(compromised -> {
                    log.warn("A rotated refresh token was presented again; revoking the authorization {}",
                            compromised.getId());
                    delegate.remove(compromised);
                });
        return null;
    }
-- Hashes of the refresh tokens that were rotated out of an authorization. Presenting one of them again means the
-- token was stolen or replayed, so the authorization is revoked.
CREATE TABLE consumed_refresh_tokens
(
    token_hash       varchar(64)              NOT NULL,
    authorization_id varchar(100)             NOT NULL REFERENCES oauth2_authorization (id) ON DELETE CASCADE,
    consumed_at      timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (token_hash)
);

CREATE INDEX ix_consumed_refresh_tokens_authorization ON consumed_refresh_tokens (authorization_id);