Refresh token rotation and reuse detection
| This documentation was generated with the assistance of AI. Please report any inaccuracies. |
A client that holds a refresh token trades it at the token endpoint for a new access token. The default clients rotate
refresh tokens (reuseRefreshTokens false), so every refresh also returns a new refresh token and the old one stops
working. Spring Authorization Server does the rotation; this repository adds reuse detection on top:
ReuseDetectingAuthorizationService, a decorator of the JDBC OAuth2AuthorizationService, records the SHA-256 hash of
each rotated-out refresh token in consumed_refresh_tokens. If one of those tokens is ever presented again, the token
was stolen or replayed, so the whole authorization is deleted: the attacker’s token and the legitimate client’s
current refresh and access tokens all stop working.
At a glance
| Item | Value |
|---|---|
Actors |
A confidential client holding a refresh token (in this repository the |
Client |
|
Preconditions |
The client was issued a refresh token by an earlier grant (for |
Endpoints |
|
Storage |
|
Steps
Normal refresh
-
The client posts
grant_type=refresh_token&refresh_token=RT1to/oauth2/token, authenticating as usual (client_secret_basicforbff). In thebffthis happens insideOAuth2AuthorizedClientManager, called byOAuth2ClientHttpRequestInterceptorwhen the access token of the session has expired. -
Spring Authorization Server calls
findByToken(RT1, refresh_token). The delegate finds the authorization, so the decorator returns it unchanged. -
The framework checks that the refresh token belongs to this client and is active, then generates a new access token, a new refresh token
RT2(rotation) and, whenopenidwas granted, a new ID token. -
It calls
save(authorization). The decorator reads the stored version first (findById), saves the new one through the delegate and, because the refresh token value changed fromRT1toRT2, inserts the hash ofRT1with the authorization id intoconsumed_refresh_tokens(ON CONFLICT DO NOTHING). -
The client receives the new access token and
RT2, and must dropRT1.
Reuse of a rotated token
-
Someone presents
RT1again (an attacker with a copy, or a client that kept the old value). -
findByToken(RT1, refresh_token)finds nothing inoauth2_authorization, because the stored authorization now holdsRT2. -
The decorator hashes
RT1and looks it up inconsumed_refresh_tokens. It finds the authorization id, logs a warning (A rotated refresh token was presented again; revoking the authorization …) and removes that authorization through the delegate. Itsconsumed_refresh_tokensrows go with it (cascade). -
The decorator returns
null, so the token endpoint answers400 invalid_grant. -
When the legitimate client next refreshes with
RT2, the authorization no longer exists and it also gets400 invalid_grant. In thebff,RestDocumentGatewayreports the failed renewal as unauthorized, the SPA gets401and starts a new sign-in.
A token that was never issued, or whose authorization was already deleted (by a previous reuse or by
ExpiredAuthorizationCleanupJob), is simply unknown: invalid_grant, nothing revoked.
The decorator and its table:
@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);
Tokens and claims
The refresh response has the same shape as the authorization code response: a new access_token (same claims as
before, roles, tenant, aud, scope; amr, acr and auth_time keep describing the original sign-in), a new
refresh_token, token_type, expires_in, scope and, with the openid scope, a new id_token.
Only hashes are stored in consumed_refresh_tokens, so the table cannot be used to obtain tokens. Lookups of other
token types (access token, device and user codes) are forwarded unchanged.
How it is tested
-
auth-server/bootTokenFlowIT:refresh_whenTokenIsValid_rotatesTheRefreshToken(new access and refresh token, one authorization) andrefresh_whenRotatedTokenIsReused_revokesTheAuthorization(the replay is refused, the authorization count drops to zero and the current refresh token is refused too); also revocation of a refresh token. -
auth-server/infrastructure/persistenceReuseDetectingAuthorizationServiceIT: over the JDBC service and PostgreSQL, a replayed rotated token revokes the authorization, and a refresh token that is not rotated records nothing. -
auth-server/infrastructure/persistenceReuseDetectingAuthorizationServiceTest: unit tests of each branch (new authorization, rotation, unchanged token, device and user codes forwarded unchanged, consumed and never-consumed tokens).