Skip to content

Commit e6f5aa8

Browse files
authored
feat: improve authenticateClient by avoiding unnecessary token creation (#2443)
1 parent cf76d6f commit e6f5aa8

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

controlplane/src/core/services/Keycloak.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { RequiredActionAlias } from '@keycloak/keycloak-admin-client/lib/defs/re
33
import { EnumStatusCode } from '@wundergraph/cosmo-connect/dist/common/common_pb';
44
import { uid } from 'uid';
55
import { FastifyBaseLogger } from 'fastify';
6+
import { decodeJwt } from 'jose';
67
import { MemberRole } from '../../db/models.js';
78
import { organizationRoleEnum } from '../../db/schema.js';
89
import { AuthenticationError } from '../errors/errors.js';
@@ -37,6 +38,29 @@ export default class Keycloak {
3738
}
3839

3940
public async authenticateClient() {
41+
if (this.client.accessToken) {
42+
// We already have an access token, determine whether the token still valid before trying to authenticate again
43+
try {
44+
const { exp } = decodeJwt(this.client.accessToken);
45+
if (exp && exp * 1000 > Date.now()) {
46+
// The access token hasn't expired
47+
return;
48+
}
49+
50+
if (this.client.refreshToken) {
51+
await this.client.auth({
52+
grantType: 'refresh_token',
53+
refreshToken: this.client.refreshToken,
54+
clientId: 'admin-cli',
55+
});
56+
57+
return;
58+
}
59+
} catch (error: unknown) {
60+
this.logger.warn(error, 'Failed to refresh the existing access token, a new token will be requested');
61+
}
62+
}
63+
4064
try {
4165
await this.client.auth({
4266
grantType: 'password',

0 commit comments

Comments
 (0)