Skip to content

Commit

Permalink
Prevents multiple requests when tokens are requested before the first…
Browse files Browse the repository at this point in the history
… token response (#525)
  • Loading branch information
adamjmcgrath authored Jul 14, 2020
1 parent 82807e3 commit 85f995e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
26 changes: 26 additions & 0 deletions __tests__/Auth0Client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ jest.mock('es-cookie');
jest.mock('../src/jwt');
jest.mock('../src/token.worker');

jest.unmock('browser-tabs-lock');

const mockWindow = <any>global;
const mockFetch = (mockWindow.fetch = <jest.Mock>unfetch);
const mockVerify = <jest.Mock>verify;
Expand Down Expand Up @@ -604,6 +606,30 @@ describe('Auth0Client', () => {
});
});

it('uses the cache for subsequent requests that occur before the response', async () => {
const auth0 = setup();
await login(auth0);
(auth0 as any).cache.clear();
jest.spyOn(<any>utils, 'runIframe').mockResolvedValue({
access_token: 'my_access_token',
state: 'MTIz'
});
mockFetch.mockResolvedValue(
fetchResponse(true, {
id_token: 'my_id_token',
access_token: 'my_access_token',
expires_in: 86400
})
);
let [access_token] = await Promise.all([
auth0.getTokenSilently(),
auth0.getTokenSilently(),
auth0.getTokenSilently()
]);
expect(access_token).toEqual('my_access_token');
expect(utils.runIframe).toHaveBeenCalledTimes(1);
});

it('uses the cache for multiple token requests with audience and scope', async () => {
const auth0 = setup();
await login(auth0);
Expand Down
5 changes: 3 additions & 2 deletions src/Auth0Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,8 @@ export default class Auth0Client {
};

try {
await lock.acquireLock(GET_TOKEN_SILENTLY_LOCK_KEY, 5000);

if (!ignoreCache) {
const cache = this.cache.get(
{
Expand All @@ -559,12 +561,11 @@ export default class Auth0Client {
);

if (cache && cache.access_token) {
await lock.releaseLock(GET_TOKEN_SILENTLY_LOCK_KEY);
return cache.access_token;
}
}

await lock.acquireLock(GET_TOKEN_SILENTLY_LOCK_KEY, 5000);

const authResult = this.options.useRefreshTokens
? await this._getTokenUsingRefreshToken(getTokenOptions)
: await this._getTokenFromIFrame(getTokenOptions);
Expand Down

0 comments on commit 85f995e

Please sign in to comment.