From 24fd0c1c1126b1f89b2f569f2a82a69d583587b9 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Mon, 24 Jul 2023 09:41:24 +0200 Subject: [PATCH] Do not crash when getTokenSilently returns null (#458) --- .../auth0-angular/src/lib/auth.service.spec.ts | 14 ++++++++++++++ projects/auth0-angular/src/lib/auth.service.ts | 15 +++++++++------ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/projects/auth0-angular/src/lib/auth.service.spec.ts b/projects/auth0-angular/src/lib/auth.service.spec.ts index 9fa5a904..83a433b6 100644 --- a/projects/auth0-angular/src/lib/auth.service.spec.ts +++ b/projects/auth0-angular/src/lib/auth.service.spec.ts @@ -776,6 +776,20 @@ describe('AuthService', () => { }); }); + it('should null when nothing in cache', (done) => { + ((auth0Client.getTokenSilently as unknown) as jest.SpyInstance).mockResolvedValue( + null + ); + + const service = createService(); + service + .getAccessTokenSilently() + .subscribe((token) => { + expect(token).toBeNull(); + done(); + }); + }); + it('should record errors in the error$ observable', (done) => { const errorObj = new Error('An error has occured'); diff --git a/projects/auth0-angular/src/lib/auth.service.ts b/projects/auth0-angular/src/lib/auth.service.ts index b3d94524..a2b61f5e 100644 --- a/projects/auth0-angular/src/lib/auth.service.ts +++ b/projects/auth0-angular/src/lib/auth.service.ts @@ -41,7 +41,8 @@ import { LogoutOptions, RedirectLoginOptions } from './interfaces'; providedIn: 'root', }) export class AuthService - implements OnDestroy { + implements OnDestroy +{ private appStateSubject$ = new ReplaySubject(1); // https://stackoverflow.com/a/41177163 @@ -242,11 +243,13 @@ export class AuthService ? client.getTokenSilently({ ...options, detailedResponse: true }) : client.getTokenSilently(options) ), - tap((token) => - this.authState.setAccessToken( - typeof token === 'string' ? token : token.access_token - ) - ), + tap((token) => { + if (token) { + this.authState.setAccessToken( + typeof token === 'string' ? token : token.access_token + ); + } + }), catchError((error) => { this.authState.setError(error); this.authState.refresh();