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 2 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
40 changes: 38 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,39 @@ 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);

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);
});
});
});
31 changes: 25 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,
USER_CACHE_KEY
} 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(USER_CACHE_KEY);

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(USER_CACHE_KEY, {
id_token,
decodedToken
});

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

const currentCache = this.userCache.get<IdTokenEntry>(
USER_CACHE_KEY
) 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.id_token === currentCache?.id_token) {
return currentCache;
} else {
this.userCache.set(USER_CACHE_KEY, cache);
}

return cache;
}

Expand Down
14 changes: 6 additions & 8 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,13 +36,10 @@ 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> {
let entry = await this.cache.get<IdTokenEntry>(
this.getIdTokenCacheKey(cacheKey.clientId)
);

if (!entry && cacheKey.scope && cacheKey.audience) {
const entryByScope = await this.get(cacheKey);
Expand Down
6 changes: 6 additions & 0 deletions src/cache/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { IdToken, User } from '../global';

export const CACHE_KEY_PREFIX = '@@auth0spajs@@';
export const CACHE_KEY_ID_TOKEN_SUFFIX = '@@user@@';
export const USER_CACHE_KEY = 'idToken';
ewanharris marked this conversation as resolved.
Show resolved Hide resolved

export type CacheKeyData = {
audience?: string;
Expand Down Expand Up @@ -66,6 +67,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