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-3588] Cache and return id token from memory so that object comparison works #975

Merged
merged 4 commits into from
Sep 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
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
3 changes: 2 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
docs
docs
static/auth0-spa-js.development_old.js
74 changes: 72 additions & 2 deletions __tests__/Auth0Client/getUser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,9 @@ describe('Auth0Client', () => {
key ===
'@@auth0spajs@@::auth0_client_id::default::openid profile email'
) {
return { body: { decodedToken: { user: { sub: '123' } } } };
return {
body: { id_token: 'abc', decodedToken: { user: { sub: '123' } } }
};
}
});

Expand All @@ -131,7 +133,7 @@ describe('Auth0Client', () => {

getMock.mockImplementation((key: string) => {
if (key === '@@auth0spajs@@::auth0_client_id::@@user@@') {
return { decodedToken: { user: { sub: '123' } } };
return { id_token: 'abc', decodedToken: { user: { sub: '123' } } };
}
});

Expand All @@ -146,5 +148,73 @@ describe('Auth0Client', () => {
);
expect(user?.sub).toBe('123');
});

it('should return from the in memory cache if no changes', async () => {
ewanharris marked this conversation as resolved.
Show resolved Hide resolved
const getMock = jest.fn();
const cache: ICache = {
get: getMock,
set: jest.fn(),
remove: jest.fn(),
allKeys: jest.fn()
};

getMock.mockImplementation((key: string) => {
if (key === '@@auth0spajs@@::auth0_client_id::@@user@@') {
return { id_token: 'abcd', decodedToken: { user: { sub: '123' } } };
}
});

const auth0 = setup({ cache });
const user = await auth0.getUser();
const secondUser = await auth0.getUser();

expect(user).toBe(secondUser);
});

it('should return a new object from the cache when the user object changes', async () => {
const getMock = jest.fn();
const cache: ICache = {
get: getMock,
set: jest.fn(),
remove: jest.fn(),
allKeys: jest.fn()
};

getMock.mockImplementation((key: string) => {
if (key === '@@auth0spajs@@::auth0_client_id::@@user@@') {
return { id_token: 'abcd', decodedToken: { user: { sub: '123' } } };
}
});

const auth0 = setup({ cache });
const user = await auth0.getUser();
const secondUser = await auth0.getUser();

expect(user).toBe(secondUser);

getMock.mockImplementation((key: string) => {
if (key === '@@auth0spajs@@::auth0_client_id::@@user@@') {
return {
id_token: 'abcdefg',
decodedToken: { user: { sub: '123' } }
};
}
});

const thirdUser = await auth0.getUser();
expect(thirdUser).not.toBe(user);
});

it('should return undefined if there is no cache entry', async () => {
const cache: ICache = {
get: jest.fn(),
set: jest.fn(),
remove: jest.fn(),
allKeys: jest.fn()
};

const auth0 = setup({ cache });
await expect(auth0.getUser()).resolves.toBe(undefined);
});
});
});
30 changes: 24 additions & 6 deletions src/Auth0Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ import {
LocalStorageCache,
CacheKey,
CacheManager,
CacheEntry
CacheEntry,
IdTokenEntry,
CACHE_KEY_ID_TOKEN_SUFFIX
} from './cache';

import { TransactionManager } from './transaction-manager';
Expand Down Expand Up @@ -171,8 +173,10 @@ export class Auth0Client {
private readonly nowProvider: () => number | Promise<number>;
private readonly httpTimeoutMs: number;
private readonly options: Auth0ClientOptions;
private readonly userCache: ICache = new InMemoryCache().enclosedCache;

cacheLocation: CacheLocation;

private worker: Worker;

private readonly defaultOptions: Partial<Auth0ClientOptions> = {
Expand All @@ -184,8 +188,7 @@ export class Auth0Client {
};

constructor(options: Auth0ClientOptions) {

this.options = {
this.options = {
...this.defaultOptions,
...options,
authorizationParams: {
Expand Down Expand Up @@ -247,9 +250,7 @@ export class Auth0Client {
this.scope = getUniqueScopes(
'openid',
this.options.authorizationParams?.scope,
this.options.useRefreshTokens ?
'offline_access' :
''
this.options.useRefreshTokens ? 'offline_access' : ''
);

this.transactionManager = new TransactionManager(
Expand Down Expand Up @@ -1000,6 +1001,7 @@ export class Auth0Client {
const postCacheClear = () => {
this.cookieStorage.remove(this.orgHintCookieName);
this.cookieStorage.remove(this.isAuthenticatedCookieName);
this.userCache.remove(CACHE_KEY_ID_TOKEN_SUFFIX);

if (localOnly) {
return;
Expand Down Expand Up @@ -1202,6 +1204,11 @@ export class Auth0Client {
private async _saveEntryInCache(entry: CacheEntry) {
const { id_token, decodedToken, ...entryWithoutIdToken } = entry;

this.userCache.set(CACHE_KEY_ID_TOKEN_SUFFIX, {
id_token,
decodedToken
});

await this.cacheManager.setIdToken(
this.options.clientId,
entry.id_token,
Expand All @@ -1221,6 +1228,17 @@ export class Auth0Client {
})
);

const currentCache = this.userCache.get<IdTokenEntry>(
CACHE_KEY_ID_TOKEN_SUFFIX
) as IdTokenEntry;

// If the id_token in the cache matches the value we previously cached in memory return the in-memory
// value so that object comparison will work
if (cache && cache.id_token === currentCache?.id_token) {
return currentCache;
}

this.userCache.set(CACHE_KEY_ID_TOKEN_SUFFIX, cache);
return cache;
}

Expand Down
22 changes: 12 additions & 10 deletions src/cache/cache-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import {
CACHE_KEY_PREFIX,
WrappedCacheEntry,
DecodedToken,
CACHE_KEY_ID_TOKEN_SUFFIX
CACHE_KEY_ID_TOKEN_SUFFIX,
IdTokenEntry
} from './shared';

const DEFAULT_EXPIRY_ADJUSTMENT_SECONDS = 0;
Expand All @@ -35,20 +36,21 @@ export class CacheManager {
await this.keyManifest?.add(cacheKey);
}

async getIdToken(
cacheKey: CacheKey
): Promise<{ id_token: string; decodedToken: DecodedToken }> {
let entry = await this.cache.get<{
id_token: string;
decodedToken: DecodedToken;
}>(this.getIdTokenCacheKey(cacheKey.clientId));
async getIdToken(cacheKey: CacheKey): Promise<IdTokenEntry | undefined> {
const entry = await this.cache.get<IdTokenEntry>(
this.getIdTokenCacheKey(cacheKey.clientId)
);

if (!entry && cacheKey.scope && cacheKey.audience) {
const entryByScope = await this.get(cacheKey);

if (!entryByScope) {
return;
}

return {
id_token: entryByScope?.id_token,
decodedToken: entryByScope?.decodedToken
id_token: entryByScope.id_token,
decodedToken: entryByScope.decodedToken
};
}

Expand Down
5 changes: 5 additions & 0 deletions src/cache/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ export interface DecodedToken {
user: User;
}

export interface IdTokenEntry {
id_token: string;
decodedToken: DecodedToken;
}

export type CacheEntry = {
id_token?: string;
access_token: string;
Expand Down
6 changes: 3 additions & 3 deletions src/global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,11 @@ export interface AuthorizationParams {
acr_values?: string;

/**
* The default scope to be used on authentication requests.
*
* The default scope to be used on authentication requests.
*
* This defaults to `profile email` if not set. If you are setting extra scopes and require
* `profile` and `email` to be included then you must include them in the provided scope.
*
*
* Note: The `openid` scope is **always applied** regardless of this setting.
*/
scope?: string;
Expand Down