Skip to content

Commit 5aead49

Browse files
Fix race condition in refresh token issuance
1 parent c041aca commit 5aead49

1 file changed

Lines changed: 27 additions & 15 deletions

File tree

packages/browser/src/__legacy__/helpers/authentication-helper.ts

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -65,13 +65,15 @@ export class AuthenticationHelper<T extends MainThreadClientConfig | WebWorkerCl
6565
protected _spaHelper: SPAHelper<T>;
6666
protected _instanceId: number;
6767
protected _isTokenRefreshing: boolean;
68+
protected _refreshAccessTokenPromise?: Promise<User>;
6869

6970
public constructor(authClient: AsgardeoAuthClient<T>, spaHelper: SPAHelper<T>) {
7071
this._authenticationClient = authClient;
7172
this._storageManager = this._authenticationClient.getStorageManager();
7273
this._spaHelper = spaHelper;
7374
this._instanceId = this._authenticationClient.getInstanceId();
7475
this._isTokenRefreshing = false;
76+
this._refreshAccessTokenPromise = undefined;
7577
}
7678

7779
public enableHttpHandler(httpClient: HttpClient): void {
@@ -174,23 +176,33 @@ export class AuthenticationHelper<T extends MainThreadClientConfig | WebWorkerCl
174176
public async refreshAccessToken(
175177
enableRetrievingSignOutURLFromSession?: (config: SPACustomGrantConfig) => void,
176178
): Promise<User> {
177-
try {
178-
await this._authenticationClient.refreshAccessToken();
179-
const customGrantConfig = await this.getCustomGrantConfigData();
180-
if (customGrantConfig) {
181-
await this.exchangeToken(customGrantConfig, enableRetrievingSignOutURLFromSession);
182-
}
183-
this._spaHelper.refreshAccessTokenAutomatically(this);
179+
if (this._refreshAccessTokenPromise) {
180+
return this._refreshAccessTokenPromise;
181+
}
184182

185-
return this._authenticationClient.getUser();
186-
} catch (error) {
187-
const refreshTokenError: Message<string> = {
188-
type: REFRESH_ACCESS_TOKEN_ERR0R,
189-
};
183+
this._refreshAccessTokenPromise = (async (): Promise<User> => {
184+
try {
185+
await this._authenticationClient.refreshAccessToken();
186+
const customGrantConfig = await this.getCustomGrantConfigData();
187+
if (customGrantConfig) {
188+
await this.exchangeToken(customGrantConfig, enableRetrievingSignOutURLFromSession);
189+
}
190+
this._spaHelper.refreshAccessTokenAutomatically(this);
190191

191-
window.postMessage(refreshTokenError);
192-
return Promise.reject(error);
193-
}
192+
return this._authenticationClient.getUser();
193+
} catch (error) {
194+
const refreshTokenError: Message<string> = {
195+
type: REFRESH_ACCESS_TOKEN_ERR0R,
196+
};
197+
198+
window.postMessage(refreshTokenError);
199+
throw error;
200+
} finally {
201+
this._refreshAccessTokenPromise = undefined;
202+
}
203+
})();
204+
205+
return this._refreshAccessTokenPromise;
194206
}
195207

196208
protected async retryFailedRequests(failedRequest: HttpRequestInterface): Promise<HttpResponse> {

0 commit comments

Comments
 (0)