Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SDK-1798] prevent unnecessary token requests #525

Merged
merged 2 commits into from
Jul 14, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -544,6 +544,8 @@ export default class Auth0Client {
};

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

if (!ignoreCache) {
const cache = this.cache.get(
{
Expand All @@ -555,12 +557,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);

// Only get an access token using a refresh token if:
// * refresh tokens are enabled
// * no audience has been specified to getTokenSilently (we can only get a token for a new audience when using an iframe)
Expand Down