From 367448f1b3c9d33206b01a4808ab76a2d6c3017f Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Tue, 26 Sep 2023 10:03:29 +0200 Subject: [PATCH 01/56] Fixed strict violations --- .../src/lib/iframe/check-session.service.ts | 65 ++++++++++++------- .../logoff-revocation.service.ts | 2 +- tsconfig.json | 2 +- 3 files changed, 45 insertions(+), 24 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/iframe/check-session.service.ts b/projects/angular-auth-oidc-client/src/lib/iframe/check-session.service.ts index 48a9b08f..791bbcf5 100644 --- a/projects/angular-auth-oidc-client/src/lib/iframe/check-session.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/iframe/check-session.service.ts @@ -1,14 +1,13 @@ import { DOCUMENT } from '@angular/common'; -import { Inject, Injectable, NgZone } from '@angular/core'; +import { Inject, Injectable, NgZone, OnDestroy } from '@angular/core'; import { BehaviorSubject, Observable, of } from 'rxjs'; import { take } from 'rxjs/operators'; +import { OpenIdConfiguration } from '../config/openid-configuration'; import { LoggerService } from '../logging/logger.service'; import { EventTypes } from '../public-events/event-types'; import { PublicEventsService } from '../public-events/public-events.service'; import { StoragePersistenceService } from '../storage/storage-persistence.service'; -import { OpenIdConfiguration } from '../config/openid-configuration'; import { IFrameService } from './existing-iframe.service'; -import { OnDestroy } from '@angular/core'; const IFRAME_FOR_CHECK_SESSION_IDENTIFIER = 'myiFrameForCheckSession'; @@ -49,17 +48,21 @@ export class CheckSessionService implements OnDestroy { ngOnDestroy(): void { this.stop(); - this.document.defaultView.removeEventListener( - 'message', - this.iframeMessageEventListener, - false - ); + const windowAsDefaultView = this.document.defaultView; + + if (windowAsDefaultView) { + windowAsDefaultView.removeEventListener( + 'message', + this.iframeMessageEventListener, + false + ); + } } isCheckSessionConfigured(configuration: OpenIdConfiguration): boolean { const { startCheckSession } = configuration; - return startCheckSession; + return Boolean(startCheckSession); } start(configuration: OpenIdConfiguration): void { @@ -84,10 +87,10 @@ export class CheckSessionService implements OnDestroy { serverStateChanged(configuration: OpenIdConfiguration): boolean { const { startCheckSession } = configuration; - return startCheckSession && this.checkSessionReceived; + return Boolean(startCheckSession) && this.checkSessionReceived; } - getExistingIframe(): HTMLIFrameElement { + getExistingIframe(): HTMLIFrameElement | null { return this.iFrameService.getExistingIFrame( IFRAME_FOR_CHECK_SESSION_IDENTIFIER ); @@ -119,16 +122,24 @@ export class CheckSessionService implements OnDestroy { // this is done even if iframe exists for HMR to work, since iframe exists on service init this.bindMessageEventToIframe(configuration); const checkSessionIframe = authWellKnownEndPoints.checkSessionIframe; + const contentWindow = existingIframe.contentWindow; - if (checkSessionIframe) { - existingIframe.contentWindow.location.replace(checkSessionIframe); - } else { + if (!checkSessionIframe) { this.loggerService.logWarning( configuration, 'CheckSession - init check session: checkSessionIframe is not configured to run' ); } + if (!contentWindow) { + this.loggerService.logWarning( + configuration, + 'CheckSession - init check session: IFrame contentWindow does not exist' + ); + } else { + contentWindow.location.replace(checkSessionIframe); + } + return new Observable((observer) => { existingIframe.onload = (): void => { this.lastIFrameRefresh = Date.now(); @@ -139,7 +150,7 @@ export class CheckSessionService implements OnDestroy { } private pollServerSession( - clientId: string, + clientId: string | undefined, configuration: OpenIdConfiguration ): void { this.outstandingMessages = 0; @@ -163,14 +174,19 @@ export class CheckSessionService implements OnDestroy { 'authWellKnownEndPoints', configuration ); + const contentWindow = existingIframe.contentWindow; - if (sessionState && authWellKnownEndPoints?.checkSessionIframe) { + if ( + sessionState && + authWellKnownEndPoints?.checkSessionIframe && + contentWindow + ) { const iframeOrigin = new URL( authWellKnownEndPoints.checkSessionIframe )?.origin; this.outstandingMessages++; - existingIframe.contentWindow.postMessage( + contentWindow.postMessage( clientId + ' ' + sessionState, iframeOrigin ); @@ -264,11 +280,16 @@ export class CheckSessionService implements OnDestroy { this, configuration ); - this.document.defaultView.addEventListener( - 'message', - this.iframeMessageEventListener, - false - ); + + const defaultView = this.document.defaultView; + + if (defaultView) { + defaultView.addEventListener( + 'message', + this.iframeMessageEventListener, + false + ); + } } private getOrCreateIframe( diff --git a/projects/angular-auth-oidc-client/src/lib/logoff-revoke/logoff-revocation.service.ts b/projects/angular-auth-oidc-client/src/lib/logoff-revoke/logoff-revocation.service.ts index 8c163e1c..986e841f 100644 --- a/projects/angular-auth-oidc-client/src/lib/logoff-revoke/logoff-revocation.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/logoff-revoke/logoff-revocation.service.ts @@ -178,7 +178,7 @@ export class LogoffRevocationService { } private logoffInternal( - logoutAuthOptions: LogoutAuthOptions, + logoutAuthOptions: LogoutAuthOptions | undefined, endSessionUrl: string, config: OpenIdConfiguration, allConfigs: OpenIdConfiguration[] diff --git a/tsconfig.json b/tsconfig.json index cbdad7cf..3605c04e 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,7 +5,7 @@ "baseUrl": "./", "outDir": "./dist/out-tsc", "forceConsistentCasingInFileNames": true, - "strict": false, + "strict": true, "paths": { "angular-auth-oidc-client": [ "dist/angular-auth-oidc-client/angular-auth-oidc-client", From c579664c798a356676d34d0480f8c5f42a671be0 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Tue, 26 Sep 2023 10:28:37 +0200 Subject: [PATCH 02/56] Fixed more strict issues --- .../src/lib/api/data.service.ts | 4 +- .../src/lib/interceptor/auth.interceptor.ts | 3 +- .../logoff-revocation.service.ts | 2 +- .../utils/collections/collections.helper.ts | 7 +++ .../src/lib/utils/url/url.service.ts | 54 +++++++++---------- 5 files changed, 39 insertions(+), 31 deletions(-) create mode 100644 projects/angular-auth-oidc-client/src/lib/utils/collections/collections.helper.ts diff --git a/projects/angular-auth-oidc-client/src/lib/api/data.service.ts b/projects/angular-auth-oidc-client/src/lib/api/data.service.ts index b16ca226..097e7dfe 100644 --- a/projects/angular-auth-oidc-client/src/lib/api/data.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/api/data.service.ts @@ -25,7 +25,7 @@ export class DataService { } post( - url: string, + url: string | null, body: any, config: OpenIdConfiguration, headersParams?: HttpHeaders @@ -33,7 +33,7 @@ export class DataService { const headers = headersParams || this.prepareHeaders(); const params = this.prepareParams(config); - return this.httpClient.post(url, body, { headers, params }); + return this.httpClient.post(url ?? '', body, { headers, params }); } private prepareHeaders(token?: string): HttpHeaders { diff --git a/projects/angular-auth-oidc-client/src/lib/interceptor/auth.interceptor.ts b/projects/angular-auth-oidc-client/src/lib/interceptor/auth.interceptor.ts index b53aa4b1..42a63adf 100644 --- a/projects/angular-auth-oidc-client/src/lib/interceptor/auth.interceptor.ts +++ b/projects/angular-auth-oidc-client/src/lib/interceptor/auth.interceptor.ts @@ -11,6 +11,7 @@ import { Observable } from 'rxjs'; import { AuthStateService } from '../auth-state/auth-state.service'; import { ConfigurationService } from '../config/config.service'; import { LoggerService } from '../logging/logger.service'; +import { flattenArray } from '../utils/collections/collections.helper'; import { ClosestMatchingRouteService } from './closest-matching-route.service'; @Injectable() @@ -64,7 +65,7 @@ function interceptRequest( const allRoutesConfigured = allConfigurations.map( (x) => x.secureRoutes || [] ); - const allRoutesConfiguredFlat = [].concat(...allRoutesConfigured) as string[]; + const allRoutesConfiguredFlat = flattenArray(allRoutesConfigured); if (allRoutesConfiguredFlat.length === 0) { deps.loggerService.logDebug( diff --git a/projects/angular-auth-oidc-client/src/lib/logoff-revoke/logoff-revocation.service.ts b/projects/angular-auth-oidc-client/src/lib/logoff-revoke/logoff-revocation.service.ts index 986e841f..769cb19a 100644 --- a/projects/angular-auth-oidc-client/src/lib/logoff-revoke/logoff-revocation.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/logoff-revoke/logoff-revocation.service.ts @@ -222,7 +222,7 @@ export class LogoffRevocationService { private sendRevokeRequest( configuration: OpenIdConfiguration, - body: string + body: string | null ): Observable { const url = this.urlService.getRevocationEndpointUrl(configuration); const headers = this.getHeaders(); diff --git a/projects/angular-auth-oidc-client/src/lib/utils/collections/collections.helper.ts b/projects/angular-auth-oidc-client/src/lib/utils/collections/collections.helper.ts new file mode 100644 index 00000000..f83619f9 --- /dev/null +++ b/projects/angular-auth-oidc-client/src/lib/utils/collections/collections.helper.ts @@ -0,0 +1,7 @@ +export function flattenArray(array: any[][]): any[] { + return array.reduce( + (flattened, elem) => + flattened.concat(Array.isArray(elem) ? flattenArray(elem) : elem), + [] + ); +} diff --git a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts index b602e48c..6c44d5af 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts @@ -49,7 +49,7 @@ export class UrlService { getRefreshSessionSilentRenewUrl( config: OpenIdConfiguration, customParams?: { [key: string]: string | number | boolean } - ): Observable { + ): Observable { if (this.flowHelper.isCurrentFlowCodeFlow(config)) { return this.createUrlCodeFlowWithSilentRenew(config, customParams); } @@ -62,7 +62,7 @@ export class UrlService { getAuthorizeParUrl( requestUri: string, configuration: OpenIdConfiguration - ): string { + ): string | null { const authWellKnownEndPoints = this.storagePersistenceService.read( 'authWellKnownEndPoints', configuration @@ -114,7 +114,7 @@ export class UrlService { getAuthorizeUrl( config: OpenIdConfiguration, authOptions?: AuthOptions - ): Observable { + ): Observable { if (this.flowHelper.isCurrentFlowCodeFlow(config)) { return this.createUrlCodeFlowAuthorize(config, authOptions); } @@ -163,7 +163,7 @@ export class UrlService { createRevocationEndpointBodyAccessToken( token: any, configuration: OpenIdConfiguration - ): string { + ): string | null { const clientId = this.getClientId(configuration); if (!clientId) { @@ -182,7 +182,7 @@ export class UrlService { createRevocationEndpointBodyRefreshToken( token: any, configuration: OpenIdConfiguration - ): string { + ): string | null { const clientId = this.getClientId(configuration); if (!clientId) { @@ -198,7 +198,7 @@ export class UrlService { return params.toString(); } - getRevocationEndpointUrl(configuration: OpenIdConfiguration): string { + getRevocationEndpointUrl(configuration: OpenIdConfiguration): string | null { const authWellKnownEndPoints = this.storagePersistenceService.read( 'authWellKnownEndPoints', configuration @@ -218,7 +218,7 @@ export class UrlService { code: string, configuration: OpenIdConfiguration, customTokenParams?: { [p: string]: string | number | boolean } - ): string { + ): string | null { const clientId = this.getClientId(configuration); if (!clientId) { @@ -278,7 +278,7 @@ export class UrlService { refreshToken: string, configuration: OpenIdConfiguration, customParamsRefresh?: { [key: string]: string | number | boolean } - ): string { + ): string | null { const clientId = this.getClientId(configuration); if (!clientId) { @@ -301,7 +301,7 @@ export class UrlService { createBodyForParCodeFlowRequest( configuration: OpenIdConfiguration, authOptions?: AuthOptions - ): Observable { + ): Observable { const redirectUrl = this.getRedirectUrl(configuration, authOptions); if (!redirectUrl) { @@ -332,10 +332,10 @@ export class UrlService { } = configuration; let params = this.createHttpParams(''); - params = params.set('client_id', clientId); + params = params.set('client_id', clientId ?? ''); params = params.append('redirect_uri', redirectUrl); - params = params.append('response_type', responseType); - params = params.append('scope', scope); + params = params.append('response_type', responseType ?? ''); + params = params.append('scope', scope ?? ''); params = params.append('nonce', nonce); params = params.append('state', state); params = params.append('code_challenge', codeChallenge); @@ -364,7 +364,7 @@ export class UrlService { ); } - getPostLogoutRedirectUrl(configuration: OpenIdConfiguration): string { + getPostLogoutRedirectUrl(configuration: OpenIdConfiguration): string | null { const { postLogoutRedirectUri } = configuration; if (!postLogoutRedirectUri) { @@ -425,7 +425,7 @@ export class UrlService { configuration: OpenIdConfiguration, prompt?: string, customRequestParams?: { [key: string]: string | number | boolean } - ): string { + ): string | null { const authWellKnownEndPoints = this.storagePersistenceService.read( 'authWellKnownEndPoints', configuration @@ -488,7 +488,7 @@ export class UrlService { if ( this.flowHelper.isCurrentFlowCodeFlow(configuration) && - codeChallenge !== null + Boolean(codeChallenge) ) { params = params.append('code_challenge', codeChallenge); params = params.append('code_challenge_method', 'S256'); @@ -514,7 +514,7 @@ export class UrlService { private createUrlImplicitFlowWithSilentRenew( configuration: OpenIdConfiguration, customParams?: { [key: string]: string | number | boolean } - ): string { + ): string | null { const state = this.flowsDataService.getExistingOrCreateAuthStateControl(configuration); const nonce = this.flowsDataService.createNonce(configuration); @@ -558,7 +558,7 @@ export class UrlService { private createUrlCodeFlowWithSilentRenew( configuration: OpenIdConfiguration, customParams?: { [key: string]: string | number | boolean } - ): Observable { + ): Observable { const state = this.flowsDataService.getExistingOrCreateAuthStateControl(configuration); const nonce = this.flowsDataService.createNonce(configuration); @@ -577,7 +577,7 @@ export class UrlService { const silentRenewUrl = this.getSilentRenewUrl(configuration); if (!silentRenewUrl) { - return ''; + return null; } const authWellKnownEndPoints = this.storagePersistenceService.read( @@ -610,7 +610,7 @@ export class UrlService { private createUrlImplicitFlowAuthorize( configuration: OpenIdConfiguration, authOptions?: AuthOptions - ): string { + ): string | null { const state = this.flowsDataService.getExistingOrCreateAuthStateControl(configuration); const nonce = this.flowsDataService.createNonce(configuration); @@ -640,7 +640,7 @@ export class UrlService { nonce, state, configuration, - null, + '', customParams ); } @@ -656,7 +656,7 @@ export class UrlService { private createUrlCodeFlowAuthorize( config: OpenIdConfiguration, authOptions?: AuthOptions - ): Observable { + ): Observable { const state = this.flowsDataService.getExistingOrCreateAuthStateControl(config); const nonce = this.flowsDataService.createNonce(config); @@ -688,7 +688,7 @@ export class UrlService { nonce, state, config, - null, + '', customParams ); } @@ -705,7 +705,7 @@ export class UrlService { private getCodeChallenge(config: OpenIdConfiguration): Observable { if (config.disablePkce) { - return of(null); + return of(''); } // code_challenge with "S256" @@ -717,7 +717,7 @@ export class UrlService { private getRedirectUrl( configuration: OpenIdConfiguration, authOptions?: AuthOptions - ): string { + ): string | null { let { redirectUrl } = configuration; if (authOptions?.redirectUrl) { @@ -738,7 +738,7 @@ export class UrlService { return redirectUrl; } - private getSilentRenewUrl(configuration: OpenIdConfiguration): string { + private getSilentRenewUrl(configuration: OpenIdConfiguration): string | null { const { silentRenewUrl } = configuration; if (!silentRenewUrl) { @@ -754,7 +754,7 @@ export class UrlService { return silentRenewUrl; } - private getClientId(configuration: OpenIdConfiguration): string { + private getClientId(configuration: OpenIdConfiguration): string | null { const { clientId } = configuration; if (!clientId) { @@ -805,7 +805,7 @@ export class UrlService { return false; } - return authority.endsWith(AUTH0_ENDPOINT) || useCustomAuth0Domain; + return authority.endsWith(AUTH0_ENDPOINT) || Boolean(useCustomAuth0Domain); } private composeAuth0Endpoint(configuration: OpenIdConfiguration): string { From 4143e2444330dc86ab3a59574f7511b461e75a61 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Tue, 26 Sep 2023 13:29:04 +0200 Subject: [PATCH 03/56] Fixed more strict issues --- .../src/lib/auth-config.ts | 4 + .../src/lib/auth-state/check-auth.service.ts | 84 ++++++++------ .../src/lib/callback/callback.service.ts | 10 +- .../callback/code-flow-callback.service.ts | 2 +- .../periodically-token-check.service.ts | 4 +- .../lib/callback/refresh-session.service.ts | 6 +- .../src/lib/config/validation/rule.ts | 6 +- .../iframe/refresh-session-iframe.service.ts | 4 +- .../src/lib/iframe/silent-renew.service.ts | 4 +- .../closest-matching-route.service.ts | 6 +- .../src/lib/login/par/par-login.service.ts | 13 +-- .../lib/login/popup/popup-login.service.ts | 18 +-- .../src/lib/login/popup/popup-result.ts | 10 +- .../src/lib/login/popup/popup.service.ts | 105 +++++++++++++----- .../login/standard/standard-login.service.ts | 4 +- .../src/lib/utils/crypto/crypto.service.ts | 2 +- .../utils/flowHelper/flow-helper.service.ts | 4 +- .../lib/utils/redirect/redirect.service.ts | 2 +- .../utils/tokenHelper/token-helper.service.ts | 6 +- .../src/lib/utils/url/current-url.service.ts | 11 +- .../lib/validation/token-validation.helper.ts | 6 +- 21 files changed, 199 insertions(+), 112 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/auth-config.ts b/projects/angular-auth-oidc-client/src/lib/auth-config.ts index a1226cb2..2bebe22b 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-config.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-config.ts @@ -13,6 +13,10 @@ export interface PassedInitialConfig { export function createStaticLoader( passedConfig: PassedInitialConfig ): StsConfigLoader { + if (!passedConfig?.config) { + throw new Error('No config provided!'); + } + return new StsConfigStaticLoader(passedConfig.config); } diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.ts index e3763549..b1379040 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.ts @@ -36,6 +36,18 @@ export class CheckAuthService { private readonly publicEventsService: PublicEventsService ) {} + private getConfig( + configuration: OpenIdConfiguration, + url: string | undefined + ): OpenIdConfiguration | null { + const stateParamFromUrl = + this.currentUrlService.getStateParamFromCurrentUrl(url); + + return Boolean(stateParamFromUrl) + ? this.getConfigurationWithUrlState([configuration], stateParamFromUrl) + : configuration; + } + checkAuth( configuration: OpenIdConfiguration, allConfigs: OpenIdConfiguration[], @@ -46,20 +58,14 @@ export class CheckAuthService { const stateParamFromUrl = this.currentUrlService.getStateParamFromCurrentUrl(url); - if (!!stateParamFromUrl) { - configuration = this.getConfigurationWithUrlState( - [configuration], - stateParamFromUrl + const config = this.getConfig(configuration, url); + if (!config) { + return throwError( + () => + new Error( + `could not find matching config for state ${stateParamFromUrl}` + ) ); - - if (!configuration) { - return throwError( - () => - new Error( - `could not find matching config for state ${stateParamFromUrl}` - ) - ); - } } return this.checkAuthWithConfig(configuration, allConfigs, url); @@ -134,14 +140,16 @@ export class CheckAuthService { this.loggerService.logError(config, errorMessage); - return of({ + const result: LoginResponse = { isAuthenticated: false, errorMessage, userData: null, idToken: '', accessToken: '', - configId: null, - }); + configId: '', + }; + + return of(result); } const currentUrl = url || this.currentUrlService.getCurrentUrl(); @@ -149,19 +157,22 @@ export class CheckAuthService { this.loggerService.logDebug( config, - `Working with config '${configId}' using ${authority}` + `Working with config '${configId}' using '${authority}'` ); if (this.popupService.isCurrentlyInPopup(config)) { - this.popupService.sendMessageToMainWindow(currentUrl); + this.popupService.sendMessageToMainWindow(currentUrl, config); - return of({ + const result: LoginResponse = { isAuthenticated: false, errorMessage: '', userData: null, idToken: '', accessToken: '', - }); + configId: '', + }; + + return of(result); } const isCallback = this.callbackService.isCallback(currentUrl); @@ -178,13 +189,18 @@ export class CheckAuthService { config, allConfigs ) - : of(null); + : of({}); return callback$.pipe( map(() => { const isAuthenticated = this.authStateService.areAuthStorageTokensValid(config); + this.loggerService.logDebug( + config, + `checkAuth completed. Firing events now. isAuthenticated: ${isAuthenticated}` + ); + if (isAuthenticated) { this.startCheckSessionAndValidation(config, allConfigs); @@ -192,25 +208,21 @@ export class CheckAuthService { this.authStateService.setAuthenticatedAndFireEvent(allConfigs); this.userService.publishUserDataIfExists(config, allConfigs); } - } - this.loggerService.logDebug( - config, - 'checkAuth completed - firing events now. isAuthenticated: ' + - isAuthenticated - ); + this.publicEventsService.fireEvent(EventTypes.CheckingAuthFinished); + } - return { + const result: LoginResponse = { isAuthenticated, userData: this.userService.getUserDataFromStore(config), accessToken: this.authStateService.getAccessToken(config), idToken: this.authStateService.getIdToken(config), configId, }; + + return result; }), tap(({ isAuthenticated }) => { - this.publicEventsService.fireEvent(EventTypes.CheckingAuthFinished); - if (isAuthenticated) { this.autoLoginService.checkSavedRedirectRouteAndNavigate(config); } @@ -222,14 +234,16 @@ export class CheckAuthService { message ); - return of({ + const result: LoginResponse = { isAuthenticated: false, errorMessage: message, userData: null, idToken: '', accessToken: '', configId, - }); + }; + + return of(result); }) ); } @@ -254,8 +268,12 @@ export class CheckAuthService { private getConfigurationWithUrlState( configurations: OpenIdConfiguration[], - stateFromUrl: string + stateFromUrl: string | null ): OpenIdConfiguration | null { + if (!stateFromUrl) { + return null; + } + for (const config of configurations) { const storedState = this.storagePersistenceService.read( 'authStateControl', diff --git a/projects/angular-auth-oidc-client/src/lib/callback/callback.service.ts b/projects/angular-auth-oidc-client/src/lib/callback/callback.service.ts index 41d9c4f5..3fd7714f 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/callback.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/callback.service.ts @@ -23,16 +23,20 @@ export class CallbackService { private readonly codeFlowCallbackService: CodeFlowCallbackService ) {} - isCallback(currentUrl: string): boolean { + isCallback(currentUrl: string | null): boolean { + if (!currentUrl) { + return false; + } + return this.urlService.isCallbackFromSts(currentUrl); } handleCallbackAndFireEvents( - currentCallbackUrl: string, + currentCallbackUrl: string | null, config: OpenIdConfiguration, allConfigs: OpenIdConfiguration[] ): Observable { - let callback$: Observable; + let callback$: Observable = new Observable(); if (this.flowHelper.isCurrentFlowCodeFlow(config)) { callback$ = this.codeFlowCallbackService.authenticatedCallbackWithCode( diff --git a/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.ts b/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.ts index 9ffa3ec6..3007cc1d 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.ts @@ -18,7 +18,7 @@ export class CodeFlowCallbackService { ) {} authenticatedCallbackWithCode( - urlToCheck: string, + urlToCheck: string | null, config: OpenIdConfiguration, allConfigs: OpenIdConfiguration[] ): Observable { diff --git a/projects/angular-auth-oidc-client/src/lib/callback/periodically-token-check.service.ts b/projects/angular-auth-oidc-client/src/lib/callback/periodically-token-check.service.ts index 29c366f7..7b6d8817 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/periodically-token-check.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/periodically-token-check.service.ts @@ -101,7 +101,7 @@ export class PeriodicallyTokenCheckService { private getRefreshEvent( config: OpenIdConfiguration, allConfigs: OpenIdConfiguration[] - ): Observable { + ): Observable { const shouldStartRefreshEvent = this.shouldStartPeriodicallyCheckForConfig(config); @@ -143,7 +143,7 @@ export class PeriodicallyTokenCheckService { private createRefreshEventForConfig( configuration: OpenIdConfiguration, allConfigs: OpenIdConfiguration[] - ): Observable { + ): Observable { this.loggerService.logDebug(configuration, 'starting silent renew...'); return this.configurationService diff --git a/projects/angular-auth-oidc-client/src/lib/callback/refresh-session.service.ts b/projects/angular-auth-oidc-client/src/lib/callback/refresh-session.service.ts index a32a2384..3ab47cfd 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/refresh-session.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/refresh-session.service.ts @@ -96,7 +96,7 @@ export class RefreshSessionService { } const { silentRenewTimeoutInSeconds } = config; - const timeOutTime = silentRenewTimeoutInSeconds * 1000; + const timeOutTime = (silentRenewTimeoutInSeconds ?? 0) * 1000; return forkJoin([ this.startRefreshSession(config, allConfigs, extraCustomParams), @@ -110,8 +110,8 @@ export class RefreshSessionService { if (isAuthenticated) { return { - idToken: callbackContext?.authResult?.id_token, - accessToken: callbackContext?.authResult?.access_token, + idToken: callbackContext?.authResult?.id_token ?? '', + accessToken: callbackContext?.authResult?.access_token ?? '', userData: this.userService.getUserDataFromStore(config), isAuthenticated, configId, diff --git a/projects/angular-auth-oidc-client/src/lib/config/validation/rule.ts b/projects/angular-auth-oidc-client/src/lib/config/validation/rule.ts index 610c75e4..69cbdd60 100644 --- a/projects/angular-auth-oidc-client/src/lib/config/validation/rule.ts +++ b/projects/angular-auth-oidc-client/src/lib/config/validation/rule.ts @@ -10,10 +10,10 @@ export interface RuleValidationResult { level: Level; } -export const POSITIVE_VALIDATION_RESULT = { +export const POSITIVE_VALIDATION_RESULT: RuleValidationResult = { result: true, messages: [], - level: null, + level: 'none', }; -export type Level = 'warning' | 'error'; +export type Level = 'warning' | 'error' | 'none'; diff --git a/projects/angular-auth-oidc-client/src/lib/iframe/refresh-session-iframe.service.ts b/projects/angular-auth-oidc-client/src/lib/iframe/refresh-session-iframe.service.ts index b468ca3a..5d6e3f93 100644 --- a/projects/angular-auth-oidc-client/src/lib/iframe/refresh-session-iframe.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/iframe/refresh-session-iframe.service.ts @@ -45,7 +45,7 @@ export class RefreshSessionIframeService { } private sendAuthorizeRequestUsingSilentRenew( - url: string, + url: string | null, config: OpenIdConfiguration, allConfigs: OpenIdConfiguration[] ): Observable { @@ -54,7 +54,7 @@ export class RefreshSessionIframeService { this.initSilentRenewRequest(config, allConfigs); this.loggerService.logDebug( config, - 'sendAuthorizeRequestUsingSilentRenew for URL:' + url + `sendAuthorizeRequestUsingSilentRenew for URL: ${url}` ); return new Observable((observer) => { diff --git a/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.ts b/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.ts index 74e4a77a..8df588f0 100644 --- a/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.ts @@ -5,6 +5,7 @@ import { catchError } from 'rxjs/operators'; import { AuthStateService } from '../auth-state/auth-state.service'; import { ImplicitFlowCallbackService } from '../callback/implicit-flow-callback.service'; import { IntervalService } from '../callback/interval.service'; +import { OpenIdConfiguration } from '../config/openid-configuration'; import { CallbackContext } from '../flows/callback-context'; import { FlowsDataService } from '../flows/flows-data.service'; import { FlowsService } from '../flows/flows.service'; @@ -12,7 +13,6 @@ import { ResetAuthDataService } from '../flows/reset-auth-data.service'; import { LoggerService } from '../logging/logger.service'; import { FlowHelper } from '../utils/flowHelper/flow-helper.service'; import { ValidationResult } from '../validation/validation-result'; -import { OpenIdConfiguration } from '../config/openid-configuration'; import { IFrameService } from './existing-iframe.service'; const IFRAME_FOR_SILENT_RENEW_IDENTIFIER = 'myiFrameForSilentRenew'; @@ -100,7 +100,7 @@ export class SilentRenewService { return this.flowsService .processSilentRenewCodeFlowCallback(callbackContext, config, allConfigs) .pipe( - catchError(() => { + catchError((error) => { this.intervalService.stopPeriodicTokenCheck(); this.resetAuthDataService.resetAuthorizationData(config, allConfigs); diff --git a/projects/angular-auth-oidc-client/src/lib/interceptor/closest-matching-route.service.ts b/projects/angular-auth-oidc-client/src/lib/interceptor/closest-matching-route.service.ts index 2b764b49..85a614a8 100644 --- a/projects/angular-auth-oidc-client/src/lib/interceptor/closest-matching-route.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/interceptor/closest-matching-route.service.ts @@ -10,7 +10,7 @@ export class ClosestMatchingRouteService { for (const config of configurations) { const { secureRoutes } = config; - for (const configuredRoute of secureRoutes) { + for (const configuredRoute of secureRoutes ?? []) { if (route.startsWith(configuredRoute)) { return { matchingRoute: configuredRoute, @@ -28,6 +28,6 @@ export class ClosestMatchingRouteService { } export interface ClosestMatchingRouteResult { - matchingRoute: string; - matchingConfig: OpenIdConfiguration; + matchingRoute: string | null; + matchingConfig: OpenIdConfiguration | null; } diff --git a/projects/angular-auth-oidc-client/src/lib/login/par/par-login.service.ts b/projects/angular-auth-oidc-client/src/lib/login/par/par-login.service.ts index f5708133..ac708d23 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/par/par-login.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/par/par-login.service.ts @@ -10,7 +10,7 @@ import { RedirectService } from '../../utils/redirect/redirect.service'; import { UrlService } from '../../utils/url/url.service'; import { LoginResponse } from '../login-response'; import { PopupOptions } from '../popup/popup-options'; -import { PopupResultReceivedUrl } from '../popup/popup-result'; +import { PopupResult } from '../popup/popup-result'; import { PopUpService } from '../popup/popup.service'; import { ResponseTypeValidationService } from '../response-type-validation/response-type-validation.service'; import { ParResponse } from './par-response'; @@ -74,7 +74,7 @@ export class ParLoginService { return; } - if (authOptions.urlHandler) { + if (authOptions?.urlHandler) { authOptions.urlHandler(url); } else { this.redirectService.redirectTo(url); @@ -116,8 +116,7 @@ export class ParLoginService { switchMap((response: ParResponse) => { this.loggerService.logDebug( configuration, - 'par response: ', - response + `par response: ${response}` ); const url = this.urlService.getAuthorizeParUrl( @@ -139,7 +138,7 @@ export class ParLoginService { return this.popupService.result$.pipe( take(1), - switchMap((result: PopupResultReceivedUrl) => { + switchMap((result: PopupResult) => { const { userClosed, receivedUrl } = result; if (userClosed) { @@ -147,8 +146,8 @@ export class ParLoginService { isAuthenticated: false, errorMessage: 'User closed popup', userData: null, - idToken: null, - accessToken: null, + idToken: '', + accessToken: '', configId, }); } diff --git a/projects/angular-auth-oidc-client/src/lib/login/popup/popup-login.service.ts b/projects/angular-auth-oidc-client/src/lib/login/popup/popup-login.service.ts index c6e57006..b61e0742 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/popup/popup-login.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/popup/popup-login.service.ts @@ -8,10 +8,10 @@ import { OpenIdConfiguration } from '../../config/openid-configuration'; import { LoggerService } from '../../logging/logger.service'; import { UrlService } from '../../utils/url/url.service'; import { LoginResponse } from '../login-response'; +import { ResponseTypeValidationService } from '../response-type-validation/response-type-validation.service'; import { PopupOptions } from './popup-options'; +import { PopupResult } from './popup-result'; import { PopUpService } from './popup.service'; -import { ResponseTypeValidationService } from '../response-type-validation/response-type-validation.service'; -import { PopupResultReceivedUrl } from './popup-result'; @Injectable({ providedIn: 'root' }) export class PopUpLoginService { @@ -55,24 +55,26 @@ export class PopUpLoginService { switchMap(() => this.urlService.getAuthorizeUrl(configuration, authOptions) ), - tap((authUrl: string) => + tap((authUrl) => this.popupService.openPopUp(authUrl, popupOptions, configuration) ), switchMap(() => { return this.popupService.result$.pipe( take(1), - switchMap((result: PopupResultReceivedUrl) => { + switchMap((result: PopupResult) => { const { userClosed, receivedUrl } = result; if (userClosed) { - return of({ + const response: LoginResponse = { isAuthenticated: false, errorMessage: 'User closed popup', userData: null, - idToken: null, - accessToken: null, + idToken: '', + accessToken: '', configId, - }); + }; + + return of(response); } return this.checkAuthService.checkAuth( diff --git a/projects/angular-auth-oidc-client/src/lib/login/popup/popup-result.ts b/projects/angular-auth-oidc-client/src/lib/login/popup/popup-result.ts index 00ee4f08..dbd44793 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/popup/popup-result.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/popup/popup-result.ts @@ -1,10 +1,4 @@ -export interface PopupResultUserClosed { - userClosed: true; -} - -export interface PopupResultReceivedUrl { - userClosed: false; +export interface PopupResult { + userClosed: boolean; receivedUrl: string; } - -export type PopupResult = PopupResultUserClosed | PopupResultReceivedUrl; diff --git a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.ts b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.ts index 0a53b633..7d39fdeb 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.ts @@ -11,9 +11,9 @@ import { PopupResult } from './popup-result'; export class PopUpService { private readonly STORAGE_IDENTIFIER = 'popupauth'; - private popUp: Window; + private popUp: Window | null = null; - private handle: number; + private handle: number = -1; private readonly resultInternal$ = new Subject(); @@ -21,7 +21,7 @@ export class PopUpService { return this.resultInternal$.asObservable(); } - private get windowInternal(): Window { + private get windowInternal(): Window | null { return this.document.defaultView; } @@ -38,10 +38,15 @@ export class PopUpService { config ); + const windowIdentifier = this.windowInternal; + if (!windowIdentifier) { + return false; + } + return ( - !!this.windowInternal.opener && - this.windowInternal.opener !== this.windowInternal && - !!popup + Boolean(windowIdentifier.opener) && + windowIdentifier.opener !== windowIdentifier && + Boolean(popup) ); } @@ -49,8 +54,8 @@ export class PopUpService { } openPopUp( - url: string, - popupOptions: PopupOptions, + url: string | null, + popupOptions: PopupOptions | undefined, config: OpenIdConfiguration ): void { const optionsToPass = this.getOptions(popupOptions); @@ -61,7 +66,18 @@ export class PopUpService { config ); - this.popUp = this.windowInternal.open(url, '_blank', optionsToPass); + const windowIdentifier = this.windowInternal; + if (!windowIdentifier) { + return; + } + + if (!url) { + this.loggerService.logError(config, 'Could not open popup, url is empty'); + + return; + } + + this.popUp = windowIdentifier.open(url, '_blank', optionsToPass); if (!this.popUp) { this.storagePersistenceService.remove(this.STORAGE_IDENTIFIER, config); @@ -89,28 +105,41 @@ export class PopUpService { this.cleanUp(listener, config); }; - this.windowInternal.addEventListener('message', listener, false); + windowIdentifier.addEventListener('message', listener, false); - this.handle = this.windowInternal.setInterval(() => { + this.handle = windowIdentifier.setInterval(() => { if (this.popUp?.closed) { - this.resultInternal$.next({ userClosed: true }); + this.resultInternal$.next({ userClosed: true, receivedUrl: '' }); this.cleanUp(listener, config); } }, 200); } - sendMessageToMainWindow(url: string): void { - if (this.windowInternal.opener) { - const href = this.windowInternal.location.href; + sendMessageToMainWindow( + url: string | null, + config: OpenIdConfiguration + ): void { + const windowIdentifier = this.windowInternal; + if (!windowIdentifier) { + return; + } + + if (windowIdentifier.opener) { + const href = windowIdentifier.location.href; - this.sendMessage(url, href); + this.sendMessage(url, href, config); } } private cleanUp(listener: any, config: OpenIdConfiguration): void { - this.windowInternal.removeEventListener('message', listener, false); - this.windowInternal.clearInterval(this.handle); + const windowIdentifier = this.windowInternal; + if (!windowIdentifier) { + return; + } + + windowIdentifier.removeEventListener('message', listener, false); + windowIdentifier.clearInterval(this.handle); if (this.popUp) { this.storagePersistenceService.remove(this.STORAGE_IDENTIFIER, config); @@ -119,12 +148,30 @@ export class PopUpService { } } - private sendMessage(url: string, href: string): void { - this.windowInternal.opener.postMessage(url, href); + private sendMessage( + url: string | null, + href: string, + config: OpenIdConfiguration + ): void { + const windowIdentifier = this.windowInternal; + if (!windowIdentifier) { + return; + } + + if (!url) { + this.loggerService.logDebug( + config, + `Can not send message to parent, no url: '${url}'` + ); + + return; + } + + windowIdentifier.opener.postMessage(url, href); } - private getOptions(popupOptions: PopupOptions): string { - const popupDefaultOptions: PopupOptions = { + private getOptions(popupOptions: PopupOptions | undefined): string { + const popupDefaultOptions = { width: 500, height: 500, left: 50, @@ -134,12 +181,18 @@ export class PopUpService { ...popupDefaultOptions, ...(popupOptions || {}), }; + const windowIdentifier = this.windowInternal; + if (!windowIdentifier) { + return ''; + } + + const width = options.width || popupDefaultOptions.width; + const height = options.height || popupDefaultOptions.height; + const left: number = - this.windowInternal.screenLeft + - (this.windowInternal.outerWidth - options.width) / 2; + windowIdentifier.screenLeft + (windowIdentifier.outerWidth - width) / 2; const top: number = - this.windowInternal.screenTop + - (this.windowInternal.outerHeight - options.height) / 2; + windowIdentifier.screenTop + (windowIdentifier.outerHeight - height) / 2; options.left = left; options.top = top; diff --git a/projects/angular-auth-oidc-client/src/lib/login/standard/standard-login.service.ts b/projects/angular-auth-oidc-client/src/lib/login/standard/standard-login.service.ts index c38e921d..290aa5d3 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/standard/standard-login.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/standard/standard-login.service.ts @@ -1,12 +1,12 @@ import { Injectable } from '@angular/core'; import { AuthOptions } from '../../auth-options'; import { AuthWellKnownService } from '../../config/auth-well-known/auth-well-known.service'; +import { OpenIdConfiguration } from '../../config/openid-configuration'; import { FlowsDataService } from '../../flows/flows-data.service'; import { LoggerService } from '../../logging/logger.service'; import { RedirectService } from '../../utils/redirect/redirect.service'; import { UrlService } from '../../utils/url/url.service'; import { ResponseTypeValidationService } from '../response-type-validation/response-type-validation.service'; -import { OpenIdConfiguration } from '../../config/openid-configuration'; @Injectable({ providedIn: 'root' }) export class StandardLoginService { @@ -48,7 +48,7 @@ export class StandardLoginService { this.urlService .getAuthorizeUrl(configuration, authOptions) - .subscribe((url: string) => { + .subscribe((url) => { if (!url) { this.loggerService.logError( configuration, diff --git a/projects/angular-auth-oidc-client/src/lib/utils/crypto/crypto.service.ts b/projects/angular-auth-oidc-client/src/lib/utils/crypto/crypto.service.ts index a41daf5c..782834d5 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/crypto/crypto.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/crypto/crypto.service.ts @@ -8,7 +8,7 @@ export class CryptoService { getCrypto(): any { // support for IE, (window.crypto || window.msCrypto) return ( - this.doc.defaultView.crypto || (this.doc.defaultView as any).msCrypto + this.doc.defaultView?.crypto || (this.doc.defaultView as any)?.msCrypto ); } } diff --git a/projects/angular-auth-oidc-client/src/lib/utils/flowHelper/flow-helper.service.ts b/projects/angular-auth-oidc-client/src/lib/utils/flowHelper/flow-helper.service.ts index d3473781..01d8ce94 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/flowHelper/flow-helper.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/flowHelper/flow-helper.service.ts @@ -19,7 +19,9 @@ export class FlowHelper { ): boolean { const { useRefreshToken } = configuration; - return this.isCurrentFlowCodeFlow(configuration) && useRefreshToken; + return ( + this.isCurrentFlowCodeFlow(configuration) && Boolean(useRefreshToken) + ); } isCurrentFlowImplicitFlowWithAccessToken( diff --git a/projects/angular-auth-oidc-client/src/lib/utils/redirect/redirect.service.ts b/projects/angular-auth-oidc-client/src/lib/utils/redirect/redirect.service.ts index 16269ce2..4888f0c9 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/redirect/redirect.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/redirect/redirect.service.ts @@ -5,7 +5,7 @@ import { Inject, Injectable } from '@angular/core'; export class RedirectService { constructor(@Inject(DOCUMENT) private readonly document: Document) {} - redirectTo(url): void { + redirectTo(url: string): void { this.document.location.href = url; } } diff --git a/projects/angular-auth-oidc-client/src/lib/utils/tokenHelper/token-helper.service.ts b/projects/angular-auth-oidc-client/src/lib/utils/tokenHelper/token-helper.service.ts index 7fb3463a..1d23f5be 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/tokenHelper/token-helper.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/tokenHelper/token-helper.service.ts @@ -113,9 +113,13 @@ export class TokenHelperService { const decoded = typeof this.document.defaultView !== 'undefined' - ? this.document.defaultView.atob(output) + ? this.document.defaultView?.atob(output) : Buffer.from(output, 'base64').toString('binary'); + if (!decoded) { + return ''; + } + try { // Going backwards: from byte stream, to percent-encoding, to original string. return decodeURIComponent( diff --git a/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.ts b/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.ts index cde0b028..cecdd266 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.ts @@ -5,15 +5,20 @@ import { Inject, Injectable } from '@angular/core'; export class CurrentUrlService { constructor(@Inject(DOCUMENT) private readonly document: Document) {} - getStateParamFromCurrentUrl(url?: string): string { + getStateParamFromCurrentUrl(url?: string): string | null { const currentUrl = url || this.getCurrentUrl(); + + if (!currentUrl) { + return null; + } + const parsedUrl = new URL(currentUrl); const urlParams = new URLSearchParams(parsedUrl.search); return urlParams.get('state'); } - getCurrentUrl(): string { - return this.document.defaultView.location.toString(); + getCurrentUrl(): string | null { + return this.document?.defaultView?.location.toString() ?? null; } } diff --git a/projects/angular-auth-oidc-client/src/lib/validation/token-validation.helper.ts b/projects/angular-auth-oidc-client/src/lib/validation/token-validation.helper.ts index 322cd050..4bc993ca 100644 --- a/projects/angular-auth-oidc-client/src/lib/validation/token-validation.helper.ts +++ b/projects/angular-auth-oidc-client/src/lib/validation/token-validation.helper.ts @@ -1,4 +1,6 @@ -export function getVerifyAlg(alg: string): RsaHashedImportParams | EcdsaParams { +export function getVerifyAlg( + alg: string +): RsaHashedImportParams | EcdsaParams | null { switch (alg.charAt(0)) { case 'R': return { @@ -39,7 +41,7 @@ export function alg2kty(alg: string): string { export function getImportAlg( alg: string -): RsaHashedImportParams | EcKeyImportParams { +): RsaHashedImportParams | EcKeyImportParams | null { switch (alg.charAt(0)) { case 'R': if (alg.includes('256')) { From 31a8c62bc89aeca0227dac8df4e9dcb17ef05e6a Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Tue, 26 Sep 2023 15:09:48 +0200 Subject: [PATCH 04/56] Solved more strict issues --- .../src/lib/auth-state/auth-state.service.ts | 16 ++++++++------ .../src/lib/auth-state/check-auth.service.ts | 21 +++++++++++++++++-- .../src/lib/callback/callback.service.ts | 4 ++-- .../callback/code-flow-callback.service.ts | 9 ++++---- .../src/lib/callback/interval.service.ts | 4 ++-- .../src/lib/config/default-config.ts | 2 +- .../src/lib/flows/callback-context.ts | 6 +++--- .../code-flow-callback-handler.service.ts | 6 +++--- .../src/lib/flows/flows-data.service.ts | 11 ++++++++-- .../src/lib/flows/flows.models.ts | 2 +- .../src/lib/flows/random/random.service.ts | 4 ++-- .../src/lib/iframe/silent-renew.service.ts | 8 +++---- .../src/lib/logging/logger.service.ts | 4 ++++ .../src/lib/login/popup/popup.service.ts | 7 ++----- .../lib/storage/browser-storage.service.ts | 20 +++++++++++++++++- .../validation/jwt-window-crypto.service.ts | 7 ++++--- 16 files changed, 89 insertions(+), 42 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.ts index 4b907d50..933b780b 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.ts @@ -80,7 +80,7 @@ export class AuthStateService { getAccessToken(configuration: OpenIdConfiguration): string { if (!this.isAuthenticated(configuration)) { - return null; + return ''; } const token = this.storagePersistenceService.getAccessToken(configuration); @@ -90,7 +90,7 @@ export class AuthStateService { getIdToken(configuration: OpenIdConfiguration): string { if (!this.isAuthenticated(configuration)) { - return null; + return ''; } const token = this.storagePersistenceService.getIdToken(configuration); @@ -100,7 +100,7 @@ export class AuthStateService { getRefreshToken(configuration: OpenIdConfiguration): string { if (!this.isAuthenticated(configuration)) { - return null; + return ''; } const token = this.storagePersistenceService.getRefreshToken(configuration); @@ -249,7 +249,9 @@ export class AuthStateService { return { isAuthenticated: true, - allConfigsAuthenticated: [{ configId, isAuthenticated: true }], + allConfigsAuthenticated: [ + { configId: configId ?? '', isAuthenticated: true }, + ], }; } @@ -264,7 +266,9 @@ export class AuthStateService { return { isAuthenticated: false, - allConfigsAuthenticated: [{ configId, isAuthenticated: false }], + allConfigsAuthenticated: [ + { configId: configId ?? '', isAuthenticated: false }, + ], }; } @@ -275,7 +279,7 @@ export class AuthStateService { allConfigs: OpenIdConfiguration[] ): AuthenticatedResult { const allConfigsAuthenticated = allConfigs.map((config) => ({ - configId: config.configId, + configId: config.configId ?? '', isAuthenticated: this.isAuthenticated(config), })); diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.ts index b1379040..71a84858 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.ts @@ -153,6 +153,24 @@ export class CheckAuthService { } const currentUrl = url || this.currentUrlService.getCurrentUrl(); + + if (!currentUrl) { + const errorMessage = 'No URL found!'; + + this.loggerService.logError(config, errorMessage); + + const result: LoginResponse = { + isAuthenticated: false, + errorMessage, + userData: null, + idToken: '', + accessToken: '', + configId: '', + }; + + return of(result); + } + const { configId, authority } = config; this.loggerService.logDebug( @@ -179,8 +197,7 @@ export class CheckAuthService { this.loggerService.logDebug( config, - 'currentUrl to check auth with: ', - currentUrl + `currentUrl to check auth with: '${currentUrl}'` ); const callback$ = isCallback diff --git a/projects/angular-auth-oidc-client/src/lib/callback/callback.service.ts b/projects/angular-auth-oidc-client/src/lib/callback/callback.service.ts index 3fd7714f..4d1fd1e1 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/callback.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/callback.service.ts @@ -23,7 +23,7 @@ export class CallbackService { private readonly codeFlowCallbackService: CodeFlowCallbackService ) {} - isCallback(currentUrl: string | null): boolean { + isCallback(currentUrl: string): boolean { if (!currentUrl) { return false; } @@ -32,7 +32,7 @@ export class CallbackService { } handleCallbackAndFireEvents( - currentCallbackUrl: string | null, + currentCallbackUrl: string, config: OpenIdConfiguration, allConfigs: OpenIdConfiguration[] ): Observable { diff --git a/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.ts b/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.ts index 3007cc1d..b6bb8290 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.ts @@ -23,11 +23,10 @@ export class CodeFlowCallbackService { allConfigs: OpenIdConfiguration[] ): Observable { const isRenewProcess = this.flowsDataService.isSilentRenewRunning(config); - const { - triggerAuthorizationResultEvent, - postLoginRoute, - unauthorizedRoute, - } = config; + const { triggerAuthorizationResultEvent } = config; + + const postLoginRoute = config.postLoginRoute || '/'; + const unauthorizedRoute = config.unauthorizedRoute || '/'; return this.flowsService .processCodeFlowCallback(urlToCheck, config, allConfigs) diff --git a/projects/angular-auth-oidc-client/src/lib/callback/interval.service.ts b/projects/angular-auth-oidc-client/src/lib/callback/interval.service.ts index 483402f9..2d196d88 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/interval.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/interval.service.ts @@ -8,7 +8,7 @@ export class IntervalService { constructor(private readonly zone: NgZone) {} isTokenValidationRunning(): boolean { - return !!this.runTokenValidationRunning; + return Boolean(this.runTokenValidationRunning); } stopPeriodicTokenCheck(): void { @@ -22,7 +22,7 @@ export class IntervalService { const millisecondsDelayBetweenTokenCheck = repeatAfterSeconds * 1000; return new Observable((subscriber) => { - let intervalId; + let intervalId: NodeJS.Timeout; this.zone.runOutsideAngular(() => { intervalId = setInterval( diff --git a/projects/angular-auth-oidc-client/src/lib/config/default-config.ts b/projects/angular-auth-oidc-client/src/lib/config/default-config.ts index 2bfd2447..29b3ee3b 100644 --- a/projects/angular-auth-oidc-client/src/lib/config/default-config.ts +++ b/projects/angular-auth-oidc-client/src/lib/config/default-config.ts @@ -4,7 +4,7 @@ import { OpenIdConfiguration } from './openid-configuration'; export const DEFAULT_CONFIG: OpenIdConfiguration = { authority: 'https://please_set', authWellknownEndpointUrl: '', - authWellknownEndpoints: null, + authWellknownEndpoints: undefined, redirectUrl: 'https://please_set', clientId: 'please_set', responseType: 'code', diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-context.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-context.ts index 71ece6ac..7caa0eb9 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-context.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-context.ts @@ -6,10 +6,10 @@ export interface CallbackContext { refreshToken: string; state: string; sessionState: string | null; - authResult: AuthResult; + authResult: AuthResult | null; isRenewProcess: boolean; - jwtKeys: JwtKeys; - validationResult: StateValidationResult; + jwtKeys: JwtKeys | null; + validationResult: StateValidationResult | null; existingIdToken: any; } diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/code-flow-callback-handler.service.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/code-flow-callback-handler.service.ts index 735de224..66fe4795 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/code-flow-callback-handler.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/code-flow-callback-handler.service.ts @@ -52,9 +52,9 @@ export class CodeFlowCallbackHandlerService { urlToCheck ); - const initialCallbackContext = { + const initialCallbackContext: CallbackContext = { code, - refreshToken: null, + refreshToken: '', state, sessionState, authResult: null, @@ -146,7 +146,7 @@ export class CodeFlowCallbackHandlerService { this.loggerService.logWarning(config, errorMessage, error); - return timer(refreshTokenRetryInSeconds * 1000); + return timer((refreshTokenRetryInSeconds ?? 0) * 1000); } return throwError(() => error); diff --git a/projects/angular-auth-oidc-client/src/lib/flows/flows-data.service.ts b/projects/angular-auth-oidc-client/src/lib/flows/flows-data.service.ts index fd5264e0..9e8b4980 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/flows-data.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/flows-data.service.ts @@ -121,7 +121,11 @@ export class FlowsDataService { return false; } - const timeOutInMilliseconds = silentRenewTimeoutInSeconds * 1000; + if (storageObject.state === 'not-running') { + return false; + } + + const timeOutInMilliseconds = (silentRenewTimeoutInSeconds ?? 0) * 1000; const dateOfLaunchedProcessUtc = Date.parse( storageObject.dateOfLaunchedProcessUtc ); @@ -175,7 +179,10 @@ export class FlowsDataService { ); if (!storageEntry) { - return null; + return { + dateOfLaunchedProcessUtc: '', + state: 'not-running', + }; } return JSON.parse(storageEntry); diff --git a/projects/angular-auth-oidc-client/src/lib/flows/flows.models.ts b/projects/angular-auth-oidc-client/src/lib/flows/flows.models.ts index 996b587e..f1089c83 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/flows.models.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/flows.models.ts @@ -3,4 +3,4 @@ export interface SilentRenewRunning { dateOfLaunchedProcessUtc: string; } -export type SilentRenewRunningState = 'running'; +export type SilentRenewRunningState = 'running' | 'not-running'; diff --git a/projects/angular-auth-oidc-client/src/lib/flows/random/random.service.ts b/projects/angular-auth-oidc-client/src/lib/flows/random/random.service.ts index 0ea5d968..34a83fca 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/random/random.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/random/random.service.ts @@ -1,7 +1,7 @@ import { Injectable } from '@angular/core'; +import { OpenIdConfiguration } from '../../config/openid-configuration'; import { LoggerService } from '../../logging/logger.service'; import { CryptoService } from '../../utils/crypto/crypto.service'; -import { OpenIdConfiguration } from '../../config/openid-configuration'; @Injectable({ providedIn: 'root' }) export class RandomService { @@ -37,7 +37,7 @@ export class RandomService { return Array.from(arr, this.toHex).join('') + this.randomString(7); } - private toHex(dec): string { + private toHex(dec: number): string { return ('0' + dec.toString(16)).substr(-2); } diff --git a/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.ts b/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.ts index 8df588f0..3c93075d 100644 --- a/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.ts @@ -20,9 +20,9 @@ const IFRAME_FOR_SILENT_RENEW_IDENTIFIER = 'myiFrameForSilentRenew'; @Injectable({ providedIn: 'root' }) export class SilentRenewService { private readonly refreshSessionWithIFrameCompletedInternal$ = - new Subject(); + new Subject(); - get refreshSessionWithIFrameCompleted$(): Observable { + get refreshSessionWithIFrameCompleted$(): Observable { return this.refreshSessionWithIFrameCompletedInternal$.asObservable(); } @@ -54,7 +54,7 @@ export class SilentRenewService { isSilentRenewConfigured(configuration: OpenIdConfiguration): boolean { const { useRefreshToken, silentRenew } = configuration; - return !useRefreshToken && silentRenew; + return !useRefreshToken && Boolean(silentRenew); } codeFlowCallbackSilentRenewIframe( @@ -152,7 +152,7 @@ export class SilentRenewService { }); } - private getExistingIframe(): HTMLIFrameElement { + private getExistingIframe(): HTMLIFrameElement | null { return this.iFrameService.getExistingIFrame( IFRAME_FOR_SILENT_RENEW_IDENTIFIER ); diff --git a/projects/angular-auth-oidc-client/src/lib/logging/logger.service.ts b/projects/angular-auth-oidc-client/src/lib/logging/logger.service.ts index cde58040..27adc32a 100644 --- a/projects/angular-auth-oidc-client/src/lib/logging/logger.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/logging/logger.service.ts @@ -111,6 +111,10 @@ export class LoggerService { ): boolean { const { logLevel } = configuration || {}; + if (!logLevel) { + return false; + } + return logLevel <= logLevelToCompare; } diff --git a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.ts b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.ts index 7d39fdeb..24670283 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.ts @@ -116,10 +116,7 @@ export class PopUpService { }, 200); } - sendMessageToMainWindow( - url: string | null, - config: OpenIdConfiguration - ): void { + sendMessageToMainWindow(url: string, config: OpenIdConfiguration): void { const windowIdentifier = this.windowInternal; if (!windowIdentifier) { return; @@ -149,7 +146,7 @@ export class PopUpService { } private sendMessage( - url: string | null, + url: string, href: string, config: OpenIdConfiguration ): void { diff --git a/projects/angular-auth-oidc-client/src/lib/storage/browser-storage.service.ts b/projects/angular-auth-oidc-client/src/lib/storage/browser-storage.service.ts index 136649b3..06a510a4 100644 --- a/projects/angular-auth-oidc-client/src/lib/storage/browser-storage.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/storage/browser-storage.service.ts @@ -13,6 +13,15 @@ export class BrowserStorageService { read(key: string, configuration: OpenIdConfiguration): any { const { configId } = configuration; + if (!configId) { + this.loggerService.logDebug( + configuration, + `Wanted to read '${key}' but configId was '${configId}'` + ); + + return null; + } + if (!this.hasStorage()) { this.loggerService.logDebug( configuration, @@ -34,10 +43,19 @@ export class BrowserStorageService { write(value: any, configuration: OpenIdConfiguration): boolean { const { configId } = configuration; + if (!configId) { + this.loggerService.logDebug( + configuration, + `Wanted to write but configId was '${configId}'` + ); + + return false; + } + if (!this.hasStorage()) { this.loggerService.logDebug( configuration, - `Wanted to write '${value}' but Storage was falsy` + `Wanted to write but Storage was falsy` ); return false; diff --git a/projects/angular-auth-oidc-client/src/lib/validation/jwt-window-crypto.service.ts b/projects/angular-auth-oidc-client/src/lib/validation/jwt-window-crypto.service.ts index 88e0374a..40312974 100644 --- a/projects/angular-auth-oidc-client/src/lib/validation/jwt-window-crypto.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/validation/jwt-window-crypto.service.ts @@ -36,8 +36,9 @@ export class JwtWindowCryptoService { return from( this.cryptoService.getCrypto().subtle.digest(algorithm, msgBuffer) ).pipe( - map((hashBuffer: ArrayBuffer) => { - const hashArray: number[] = Array.from(new Uint8Array(hashBuffer)); + map((hashBuffer: unknown) => { + const buffer = hashBuffer as ArrayBuffer; + const hashArray: number[] = Array.from(new Uint8Array(buffer)); return this.toHashString(hashArray); }) @@ -54,7 +55,7 @@ export class JwtWindowCryptoService { return result; } - private base64UrlEncode(str): string { + private base64UrlEncode(str: string): string { const base64: string = btoa(str); return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); From 90113ca15985f567f5d9fdf64e5fdd3b196878f0 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Tue, 26 Sep 2023 19:34:30 +0200 Subject: [PATCH 05/56] MOre strict issues --- .../src/lib/callback/code-flow-callback.service.ts | 2 +- .../src/lib/callback/interval.service.ts | 4 ++-- .../history-jwt-keys-callback-handler.service.ts | 6 +++--- .../lib/iframe/refresh-session-iframe.service.ts | 4 ++-- .../src/lib/iframe/silent-renew.service.ts | 8 ++++---- .../src/lib/user-data/user.service.ts | 14 +++++++++----- .../src/lib/utils/url/url.service.ts | 4 +--- .../lib/validation/jwk-window-crypto.service.ts | 3 ++- .../src/lib/validation/state-validation.service.ts | 10 ++++++---- .../src/lib/validation/token-validation.service.ts | 6 ++---- 10 files changed, 32 insertions(+), 29 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.ts b/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.ts index b6bb8290..a1f2dca6 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.ts @@ -18,7 +18,7 @@ export class CodeFlowCallbackService { ) {} authenticatedCallbackWithCode( - urlToCheck: string | null, + urlToCheck: string, config: OpenIdConfiguration, allConfigs: OpenIdConfiguration[] ): Observable { diff --git a/projects/angular-auth-oidc-client/src/lib/callback/interval.service.ts b/projects/angular-auth-oidc-client/src/lib/callback/interval.service.ts index 2d196d88..54c0fa35 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/interval.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/interval.service.ts @@ -1,9 +1,9 @@ import { Injectable, NgZone } from '@angular/core'; -import { Observable } from 'rxjs'; +import { Observable, Subscription } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class IntervalService { - runTokenValidationRunning = null; + runTokenValidationRunning: Subscription | null = null; constructor(private readonly zone: NgZone) {} diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/history-jwt-keys-callback-handler.service.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/history-jwt-keys-callback-handler.service.ts index b6c0fc1d..a77936ff 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/history-jwt-keys-callback-handler.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/history-jwt-keys-callback-handler.service.ts @@ -50,7 +50,7 @@ export class HistoryJwtKeysCallbackHandlerService { if ( config.allowUnsafeReuseRefreshToken && - callbackContext.authResult.refresh_token + callbackContext.authResult?.refresh_token ) { this.storagePersistenceService.write( 'reusable_refresh_token', @@ -68,7 +68,7 @@ export class HistoryJwtKeysCallbackHandlerService { this.loggerService.logDebug(config, 'history clean up inactive'); } - if (callbackContext.authResult.error) { + if (callbackContext.authResult?.error) { const errorMessage = `AuthCallback AuthResult came with error: ${callbackContext.authResult.error}`; this.loggerService.logDebug(config, errorMessage); @@ -156,7 +156,7 @@ export class HistoryJwtKeysCallbackHandlerService { } private resetBrowserHistory(): void { - this.document.defaultView.history.replaceState( + this.document.defaultView?.history.replaceState( {}, this.document.title, this.document.defaultView.location.origin + diff --git a/projects/angular-auth-oidc-client/src/lib/iframe/refresh-session-iframe.service.ts b/projects/angular-auth-oidc-client/src/lib/iframe/refresh-session-iframe.service.ts index 5d6e3f93..eb473a72 100644 --- a/projects/angular-auth-oidc-client/src/lib/iframe/refresh-session-iframe.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/iframe/refresh-session-iframe.service.ts @@ -69,7 +69,7 @@ export class RefreshSessionIframeService { }; sessionIframe.addEventListener('load', onLoadHandler); - sessionIframe.contentWindow.location.replace(url); + sessionIframe.contentWindow?.location.replace(url ?? ''); }); } @@ -96,7 +96,7 @@ export class RefreshSessionIframeService { this.silentRenewService.silentRenewEventHandler(e, config, allConfigs) ); - this.document.defaultView.dispatchEvent( + this.document.defaultView?.dispatchEvent( new CustomEvent('oidc-silent-renew-init', { detail: instanceId, }) diff --git a/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.ts b/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.ts index 3c93075d..889aa497 100644 --- a/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.ts @@ -81,13 +81,13 @@ export class SilentRenewService { return throwError(() => new Error(error)); } - const code = params.get('code'); - const state = params.get('state'); + const code = params.get('code') ?? ''; + const state = params.get('state') ?? ''; const sessionState = params.get('session_state'); - const callbackContext = { + const callbackContext: CallbackContext = { code, - refreshToken: null, + refreshToken: '', state, sessionState, authResult: null, diff --git a/projects/angular-auth-oidc-client/src/lib/user-data/user.service.ts b/projects/angular-auth-oidc-client/src/lib/user-data/user.service.ts index ba7a397a..1a5ea321 100644 --- a/projects/angular-auth-oidc-client/src/lib/user-data/user.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/user-data/user.service.ts @@ -274,20 +274,24 @@ export class UserService { if (!hasManyConfigs) { const { configId } = currentConfiguration; - return this.composeSingleUserDataResult(configId, passedUserData); + return this.composeSingleUserDataResult(configId ?? '', passedUserData); } const allUserData: ConfigUserDataResult[] = allConfigs.map((config) => { - const { configId } = currentConfiguration; + const currentConfigId = currentConfiguration.configId ?? ''; + const configId = config.configId ?? ''; - if (this.currentConfigIsToUpdate(configId, config)) { - return { configId: config.configId, userData: passedUserData }; + if (this.currentConfigIsToUpdate(currentConfigId, config)) { + return { configId, userData: passedUserData }; } const alreadySavedUserData = this.storagePersistenceService.read('userData', config) || null; - return { configId: config.configId, userData: alreadySavedUserData }; + return { + configId, + userData: alreadySavedUserData, + }; }); return { diff --git a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts index 6c44d5af..cf5860da 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts @@ -54,9 +54,7 @@ export class UrlService { return this.createUrlCodeFlowWithSilentRenew(config, customParams); } - return of( - this.createUrlImplicitFlowWithSilentRenew(config, customParams) || '' - ); + return of(this.createUrlImplicitFlowWithSilentRenew(config, customParams)); } getAuthorizeParUrl( diff --git a/projects/angular-auth-oidc-client/src/lib/validation/jwk-window-crypto.service.ts b/projects/angular-auth-oidc-client/src/lib/validation/jwk-window-crypto.service.ts index 38b96cfd..8654adbb 100644 --- a/projects/angular-auth-oidc-client/src/lib/validation/jwk-window-crypto.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/validation/jwk-window-crypto.service.ts @@ -13,6 +13,7 @@ export class JwkWindowCryptoService { | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm + | null ): Promise { return this.cryptoService .getCrypto() @@ -20,7 +21,7 @@ export class JwkWindowCryptoService { } verifyKey( - verifyAlgorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams, + verifyAlgorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | null, cryptoKey: CryptoKey, signature: BufferSource, signingInput: string diff --git a/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.ts b/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.ts index cb8ca980..348e44d0 100644 --- a/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.ts @@ -27,7 +27,10 @@ export class StateValidationService { callbackContext: CallbackContext, configuration: OpenIdConfiguration ): Observable { - if (!callbackContext || callbackContext.authResult.error) { + const hasError = Boolean(callbackContext.authResult?.error); + const hasCallbackContext = Boolean(callbackContext); + + if (!hasCallbackContext || hasError) { return of(new StateValidationResult('', '', false, {})); } @@ -46,7 +49,7 @@ export class StateValidationService { if ( !this.tokenValidationService.validateStateFromHashCallback( - callbackContext.authResult.state, + callbackContext.authResult?.state, authStateControl, configuration ) @@ -67,14 +70,13 @@ export class StateValidationService { this.flowHelper.isCurrentFlowCodeFlow(configuration); if (isCurrentFlowImplicitFlowWithAccessToken || isCurrentFlowCodeFlow) { - toReturn.accessToken = callbackContext.authResult.access_token; + toReturn.accessToken = callbackContext.authResult?.access_token ?? ''; } const disableIdTokenValidation = configuration.disableIdTokenValidation; if (disableIdTokenValidation) { toReturn.state = ValidationResult.Ok; - // TODO TESTING toReturn.authResponseIsValid = true; return of(toReturn); diff --git a/projects/angular-auth-oidc-client/src/lib/validation/token-validation.service.ts b/projects/angular-auth-oidc-client/src/lib/validation/token-validation.service.ts index 08fdeafc..d37894b8 100644 --- a/projects/angular-auth-oidc-client/src/lib/validation/token-validation.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/validation/token-validation.service.ts @@ -479,8 +479,7 @@ export class TokenValidationService { return of(false); } - const algorithm: RsaHashedImportParams | EcKeyImportParams = - getImportAlg(alg); + const algorithm = getImportAlg(alg); const signingInput = this.tokenHelperService.getSigningInputFromToken( idToken, @@ -501,8 +500,7 @@ export class TokenValidationService { loose: true, }); - const verifyAlgorithm: RsaHashedImportParams | EcdsaParams = - getVerifyAlg(alg); + const verifyAlgorithm = getVerifyAlg(alg); return from( this.jwkWindowCryptoService.verifyKey( From 6bd1b7bd2dd954e562eb573f882b99cf071e83b9 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Tue, 26 Sep 2023 19:53:21 +0200 Subject: [PATCH 06/56] more issues fixed --- .../src/lib/auth-state/auth-state.service.ts | 2 +- .../implicit-flow-callback.service.ts | 10 +++++----- .../periodically-token-check.service.ts | 20 ++++++++++++------- .../src/lib/extractors/jwk.extractor.ts | 2 +- .../src/lib/flows/callback-context.ts | 2 ++ .../validation/state-validation.service.ts | 13 ++++++------ 6 files changed, 28 insertions(+), 21 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.ts index 933b780b..e263caca 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.ts @@ -225,7 +225,7 @@ export class AuthStateService { } private persistAccessTokenExpirationTime( - authResult: any, + authResult: AuthResult | null, configuration: OpenIdConfiguration ): void { if (authResult?.expires_in) { diff --git a/projects/angular-auth-oidc-client/src/lib/callback/implicit-flow-callback.service.ts b/projects/angular-auth-oidc-client/src/lib/callback/implicit-flow-callback.service.ts index c2ac2250..d7a03828 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/implicit-flow-callback.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/implicit-flow-callback.service.ts @@ -23,11 +23,11 @@ export class ImplicitFlowCallbackService { hash?: string ): Observable { const isRenewProcess = this.flowsDataService.isSilentRenewRunning(config); - const { - triggerAuthorizationResultEvent, - postLoginRoute, - unauthorizedRoute, - } = config; + const triggerAuthorizationResultEvent = Boolean( + config.triggerAuthorizationResultEvent + ); + const postLoginRoute = config.postLoginRoute ?? ''; + const unauthorizedRoute = config.unauthorizedRoute ?? ''; return this.flowsService .processImplicitFlowCallback(config, allConfigs, hash) diff --git a/projects/angular-auth-oidc-client/src/lib/callback/periodically-token-check.service.ts b/projects/angular-auth-oidc-client/src/lib/callback/periodically-token-check.service.ts index 7b6d8817..6ba61e91 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/periodically-token-check.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/periodically-token-check.service.ts @@ -56,11 +56,15 @@ export class PeriodicallyTokenCheckService { .startPeriodicTokenCheck(refreshTimeInSeconds) .pipe( switchMap(() => { - const objectWithConfigIdsAndRefreshEvent = {}; + const objectWithConfigIdsAndRefreshEvent: { + [id: string]: Observable; + } = {}; configsWithSilentRenewEnabled.forEach((config) => { - objectWithConfigIdsAndRefreshEvent[config.configId] = - this.getRefreshEvent(config, allConfigs); + const identifier = config.configId as string; + const refreshEvent = this.getRefreshEvent(config, allConfigs); + + objectWithConfigIdsAndRefreshEvent[identifier] = refreshEvent; }); return forkJoin(objectWithConfigIdsAndRefreshEvent); @@ -101,7 +105,7 @@ export class PeriodicallyTokenCheckService { private getRefreshEvent( config: OpenIdConfiguration, allConfigs: OpenIdConfiguration[] - ): Observable { + ): Observable { const shouldStartRefreshEvent = this.shouldStartPeriodicallyCheckForConfig(config); @@ -128,10 +132,12 @@ export class PeriodicallyTokenCheckService { configsWithSilentRenewEnabled: OpenIdConfiguration[] ): number { const result = configsWithSilentRenewEnabled.reduce((prev, curr) => - prev.tokenRefreshInSeconds < curr.tokenRefreshInSeconds ? prev : curr + (prev.tokenRefreshInSeconds ?? 0) < (curr.tokenRefreshInSeconds ?? 0) + ? prev + : curr ); - return result.tokenRefreshInSeconds; + return result.tokenRefreshInSeconds ?? 0; } private getConfigsWithSilentRenewEnabled( @@ -143,7 +149,7 @@ export class PeriodicallyTokenCheckService { private createRefreshEventForConfig( configuration: OpenIdConfiguration, allConfigs: OpenIdConfiguration[] - ): Observable { + ): Observable { this.loggerService.logDebug(configuration, 'starting silent renew...'); return this.configurationService diff --git a/projects/angular-auth-oidc-client/src/lib/extractors/jwk.extractor.ts b/projects/angular-auth-oidc-client/src/lib/extractors/jwk.extractor.ts index 54016e42..7c93a127 100644 --- a/projects/angular-auth-oidc-client/src/lib/extractors/jwk.extractor.ts +++ b/projects/angular-auth-oidc-client/src/lib/extractors/jwk.extractor.ts @@ -12,7 +12,7 @@ export class JwkExtractor { } const foundKeys = keys - .filter((k) => (spec?.kid ? k['kid'] === spec.kid : true)) + .filter((k) => (spec?.kid ? (k as any)['kid'] === spec.kid : true)) .filter((k) => (spec?.use ? k['use'] === spec.use : true)) .filter((k) => (spec?.kty ? k['kty'] === spec.kty : true)); diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-context.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-context.ts index 7caa0eb9..e2bcc921 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-context.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-context.ts @@ -24,4 +24,6 @@ export interface AuthResult { // eslint-disable-next-line @typescript-eslint/naming-convention session_state?: any; state?: any; + // eslint-disable-next-line @typescript-eslint/naming-convention + expires_in?: number; } diff --git a/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.ts b/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.ts index 348e44d0..a19860d4 100644 --- a/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.ts @@ -84,17 +84,16 @@ export class StateValidationService { const isInRefreshTokenFlow = callbackContext.isRenewProcess && !!callbackContext.refreshToken; - const hasIdToken = !!callbackContext.authResult.id_token; + const hasIdToken = Boolean(callbackContext.authResult?.id_token); if (isInRefreshTokenFlow && !hasIdToken) { toReturn.state = ValidationResult.Ok; - // TODO TESTING toReturn.authResponseIsValid = true; return of(toReturn); } - if (callbackContext.authResult.id_token) { + if (hasIdToken) { const { clientId, issValidationOff, @@ -104,7 +103,7 @@ export class StateValidationService { renewTimeBeforeTokenExpiresInSeconds, } = configuration; - toReturn.idToken = callbackContext.authResult.id_token; + toReturn.idToken = callbackContext.authResult?.id_token ?? ''; toReturn.decodedIdToken = this.tokenHelperService.getPayloadFromToken( toReturn.idToken, false, @@ -139,7 +138,7 @@ export class StateValidationService { !this.tokenValidationService.validateIdTokenNonce( toReturn.decodedIdToken, authNonce, - ignoreNonceAfterRefresh, + Boolean(ignoreNonceAfterRefresh), configuration ) ) { @@ -173,8 +172,8 @@ export class StateValidationService { !isInRefreshTokenFlow && !this.tokenValidationService.validateIdTokenIatMaxOffset( toReturn.decodedIdToken, - maxIdTokenIatOffsetAllowedInSeconds, - disableIatOffsetValidation, + maxIdTokenIatOffsetAllowedInSeconds ?? 120, + Boolean(disableIatOffsetValidation), configuration ) ) { From 265a1d03c1db5b47b9f13661545e581f874dd184 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Thu, 28 Sep 2023 17:48:03 +0200 Subject: [PATCH 07/56] Fixed more strict mode issues --- .../src/lib/auth-state/auth-state.service.ts | 8 ++++- .../src/lib/auto-login/auto-login.service.ts | 5 +++- .../src/lib/config/config.service.ts | 30 ++++++++++++------- .../code-flow-callback-handler.service.ts | 16 ++++++---- .../user-callback-handler.service.ts | 4 +-- .../src/lib/utils/url/url.service.ts | 6 +++- 6 files changed, 47 insertions(+), 22 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.ts index e263caca..d6d6f893 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.ts @@ -118,7 +118,13 @@ export class AuthStateService { ); } - areAuthStorageTokensValid(configuration: OpenIdConfiguration): boolean { + areAuthStorageTokensValid( + configuration: OpenIdConfiguration | null + ): boolean { + if (!configuration) { + return false; + } + if (!this.isAuthenticated(configuration)) { return false; } diff --git a/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login.service.ts b/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login.service.ts index 7092e74d..5520c7ff 100644 --- a/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login.service.ts @@ -12,7 +12,10 @@ export class AutoLoginService { private readonly router: Router ) {} - checkSavedRedirectRouteAndNavigate(config: OpenIdConfiguration): void { + checkSavedRedirectRouteAndNavigate(config: OpenIdConfiguration | null): void { + if (!config) { + return; + } const savedRouteForRedirect = this.getStoredRedirectRoute(config); if (savedRouteForRedirect != null) { diff --git a/projects/angular-auth-oidc-client/src/lib/config/config.service.ts b/projects/angular-auth-oidc-client/src/lib/config/config.service.ts index d44e6d8b..54362276 100644 --- a/projects/angular-auth-oidc-client/src/lib/config/config.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/config/config.service.ts @@ -34,7 +34,9 @@ export class ConfigurationService { return Object.values(this.configsInternal); } - getOpenIDConfiguration(configId?: string): Observable { + getOpenIDConfiguration( + configId?: string + ): Observable { if (this.configsAlreadySaved()) { return of(this.getConfig(configId)); } @@ -44,9 +46,10 @@ export class ConfigurationService { ); } - getOpenIDConfigurations( - configId?: string - ): Observable<{ allConfigs; currentConfig }> { + getOpenIDConfigurations(configId?: string): Observable<{ + allConfigs: OpenIdConfiguration[]; + currentConfig: OpenIdConfiguration | null; + }> { return this.loadConfigs().pipe( concatMap((allConfigs) => this.prepareAndSaveConfigs(allConfigs)), map((allPreparedConfigs) => ({ @@ -63,7 +66,7 @@ export class ConfigurationService { private saveConfig(readyConfig: OpenIdConfiguration): void { const { configId } = readyConfig; - this.configsInternal[configId] = readyConfig; + this.configsInternal[configId as string] = readyConfig; } private loadConfigs(): Observable { @@ -74,9 +77,9 @@ export class ConfigurationService { return this.hasAtLeastOneConfig(); } - private getConfig(configId: string): OpenIdConfiguration { - if (!!configId) { - return this.configsInternal[configId] || null; + private getConfig(configId?: string): OpenIdConfiguration | null { + if (Boolean(configId)) { + return this.configsInternal[configId as string] || null; } const [, value] = Object.entries(this.configsInternal)[0] || [[null, null]]; @@ -88,13 +91,18 @@ export class ConfigurationService { passedConfigs: OpenIdConfiguration[] ): Observable { if (!this.configValidationService.validateConfigs(passedConfigs)) { - return of(null); + return of([]); } this.createUniqueIds(passedConfigs); + const allHandleConfigs$ = passedConfigs.map((x) => this.handleConfig(x)); + const as = forkJoin(allHandleConfigs$).pipe( + map((x) => x.filter((y) => Boolean(y))), + map((z) => z as OpenIdConfiguration[]) + ); - return forkJoin(allHandleConfigs$); + return as; } private createUniqueIds(passedConfigs: OpenIdConfiguration[]): void { @@ -107,7 +115,7 @@ export class ConfigurationService { private handleConfig( passedConfig: OpenIdConfiguration - ): Observable { + ): Observable { if (!this.configValidationService.validateConfig(passedConfig)) { this.loggerService.logError( passedConfig, diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/code-flow-callback-handler.service.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/code-flow-callback-handler.service.ts index 66fe4795..7664818e 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/code-flow-callback-handler.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/code-flow-callback-handler.service.ts @@ -107,12 +107,16 @@ export class CodeFlowCallbackHandlerService { return this.dataService .post(tokenEndpoint, bodyForCodeFlow, config, headers) .pipe( - switchMap((response: AuthResult) => { - callbackContext.authResult = { - ...response, - state: callbackContext.state, - session_state: callbackContext.sessionState, - }; + switchMap((response) => { + if (response) { + const authResult: AuthResult = { + ...response, + state: callbackContext.state, + session_state: callbackContext.sessionState, + }; + + callbackContext.authResult = authResult; + } return of(callbackContext); }), diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/user-callback-handler.service.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/user-callback-handler.service.ts index af4e88a8..fb0e4f56 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/user-callback-handler.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/user-callback-handler.service.ts @@ -33,7 +33,7 @@ export class UserCallbackHandlerService { if (!autoUserInfo) { if (!isRenewProcess || renewUserInfoAfterTokenRenew) { // userData is set to the id_token decoded, auto get user data set to false - if (validationResult.decodedIdToken) { + if (validationResult?.decodedIdToken) { this.userService.setUserDataToStore( validationResult.decodedIdToken, configuration, @@ -44,7 +44,7 @@ export class UserCallbackHandlerService { if (!isRenewProcess && !refreshToken) { this.flowsDataService.setSessionState( - authResult.session_state, + authResult?.session_state, configuration ); } diff --git a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts index cf5860da..c1037e6e 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts @@ -110,9 +110,13 @@ export class UrlService { } getAuthorizeUrl( - config: OpenIdConfiguration, + config: OpenIdConfiguration | null, authOptions?: AuthOptions ): Observable { + if (!config) { + return of(null); + } + if (this.flowHelper.isCurrentFlowCodeFlow(config)) { return this.createUrlCodeFlowAuthorize(config, authOptions); } From b638a34428295f71884dc3ae566417961598656c Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Thu, 28 Sep 2023 17:58:12 +0200 Subject: [PATCH 08/56] More strict issues --- .../src/lib/auth-state/auth-state.service.ts | 2 +- .../implicit-flow-callback-handler.service.ts | 8 +-- ...efresh-session-callback-handler.service.ts | 4 +- .../refresh-token-callback-handler.service.ts | 53 ++++++++++--------- .../user-callback-handler.service.ts | 4 +- .../validation/state-validation.service.ts | 2 +- .../validation/token-validation.service.ts | 7 ++- 7 files changed, 43 insertions(+), 37 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.ts index d6d6f893..b25308a2 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.ts @@ -60,7 +60,7 @@ export class AuthStateService { setAuthorizationData( accessToken: string, - authResult: AuthResult, + authResult: AuthResult | null, currentConfig: OpenIdConfiguration, allConfigs: OpenIdConfiguration[] ): void { diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/implicit-flow-callback-handler.service.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/implicit-flow-callback-handler.service.ts index a9aac2ad..e88694c6 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/implicit-flow-callback-handler.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/implicit-flow-callback-handler.service.ts @@ -43,10 +43,10 @@ export class ImplicitFlowCallbackHandlerService { return resultData; }, {}); - const callbackContext = { - code: null, - refreshToken: null, - state: null, + const callbackContext: CallbackContext = { + code: '', + refreshToken: '', + state: '', sessionState: null, authResult, isRenewProcess: isRenewProcessData, diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-session-callback-handler.service.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-session-callback-handler.service.ts index fc6c3b95..dd667c31 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-session-callback-handler.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-session-callback-handler.service.ts @@ -30,8 +30,8 @@ export class RefreshSessionCallbackHandlerService { const idToken = this.authStateService.getIdToken(config); if (refreshToken) { - const callbackContext = { - code: null, + const callbackContext: CallbackContext = { + code: '', refreshToken, state: stateData, sessionState: null, diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-token-callback-handler.service.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-token-callback-handler.service.ts index 8297f5b4..1c1772a6 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-token-callback-handler.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-token-callback-handler.service.ts @@ -44,30 +44,33 @@ export class RefreshTokenCallbackHandlerService { customParamsRefresh ); - return this.dataService.post(tokenEndpoint, data, config, headers).pipe( - switchMap((response: AuthResult) => { - this.loggerService.logDebug( - config, - 'token refresh response: ', - response - ); - - response.state = callbackContext.state; - - callbackContext.authResult = response; - - return of(callbackContext); - }), - retryWhen((error) => this.handleRefreshRetry(error, config)), - catchError((error) => { - const { authority } = config; - const errorMessage = `OidcService code request ${authority}`; - - this.loggerService.logError(config, errorMessage, error); - - return throwError(() => new Error(errorMessage)); - }) - ); + return this.dataService + .post(tokenEndpoint, data, config, headers) + .pipe( + switchMap((response) => { + this.loggerService.logDebug( + config, + `token refresh response: ${response}` + ); + + if (response) { + response.state = callbackContext.state; + } + + callbackContext.authResult = response; + + return of(callbackContext); + }), + retryWhen((error) => this.handleRefreshRetry(error, config)), + catchError((error) => { + const { authority } = config; + const errorMessage = `OidcService code request ${authority}`; + + this.loggerService.logError(config, errorMessage, error); + + return throwError(() => new Error(errorMessage)); + }) + ); } private handleRefreshRetry( @@ -88,7 +91,7 @@ export class RefreshTokenCallbackHandlerService { this.loggerService.logWarning(config, errorMessage, error); - return timer(refreshTokenRetryInSeconds * 1000); + return timer((refreshTokenRetryInSeconds ?? 0) * 1000); } return throwError(() => error); diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/user-callback-handler.service.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/user-callback-handler.service.ts index fb0e4f56..622b8cef 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/user-callback-handler.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/user-callback-handler.service.ts @@ -59,8 +59,8 @@ export class UserCallbackHandlerService { configuration, allConfigs, isRenewProcess, - validationResult.idToken, - validationResult.decodedIdToken + validationResult?.idToken, + validationResult?.decodedIdToken ) .pipe( switchMap((userData) => { diff --git a/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.ts b/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.ts index a19860d4..a975cdf5 100644 --- a/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.ts @@ -353,7 +353,7 @@ export class StateValidationService { } // only do check if id_token returned, no always the case when using refresh tokens - if (callbackContext.authResult.id_token) { + if (callbackContext.authResult?.id_token) { const idTokenHeader = this.tokenHelperService.getHeaderFromToken( toReturn.idToken, false, diff --git a/projects/angular-auth-oidc-client/src/lib/validation/token-validation.service.ts b/projects/angular-auth-oidc-client/src/lib/validation/token-validation.service.ts index d37894b8..4bea89d5 100644 --- a/projects/angular-auth-oidc-client/src/lib/validation/token-validation.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/validation/token-validation.service.ts @@ -335,7 +335,7 @@ export class TokenValidationService { // not trusted by the Client. validateIdTokenAud( dataIdToken: any, - aud: any, + aud: string | undefined, configuration: OpenIdConfiguration ): boolean { if (Array.isArray(dataIdToken.aud)) { @@ -382,7 +382,10 @@ export class TokenValidationService { } // If an azp (authorized party) Claim is present, the Client SHOULD verify that its client_id is the Claim Value. - validateIdTokenAzpValid(dataIdToken: any, clientId: string): boolean { + validateIdTokenAzpValid( + dataIdToken: any, + clientId: string | undefined + ): boolean { if (!dataIdToken?.azp) { return true; } From 3f8c44b83521c54f27dd3340f1538580a3c324c1 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Mon, 2 Oct 2023 20:27:58 +0200 Subject: [PATCH 09/56] Fixed linting --- .../src/lib/auth-state/check-auth.service.ts | 2 +- .../src/lib/iframe/silent-renew.service.ts | 6 +++--- .../src/lib/login/popup/popup.service.ts | 8 +++++++- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.ts index 71a84858..e7bb9bc5 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.ts @@ -57,8 +57,8 @@ export class CheckAuthService { const stateParamFromUrl = this.currentUrlService.getStateParamFromCurrentUrl(url); - const config = this.getConfig(configuration, url); + if (!config) { return throwError( () => diff --git a/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.ts b/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.ts index 889aa497..1c0941c4 100644 --- a/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.ts @@ -66,9 +66,9 @@ export class SilentRenewService { fromString: urlParts[1], }); - const error = params.get('error'); + const errorParam = params.get('error'); - if (error) { + if (errorParam) { this.authStateService.updateAndPublishAuthState({ isAuthenticated: false, validationResult: ValidationResult.LoginRequired, @@ -78,7 +78,7 @@ export class SilentRenewService { this.flowsDataService.setNonce('', config); this.intervalService.stopPeriodicTokenCheck(); - return throwError(() => new Error(error)); + return throwError(() => new Error(errorParam)); } const code = params.get('code') ?? ''; diff --git a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.ts b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.ts index 24670283..cc05a049 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.ts @@ -13,7 +13,7 @@ export class PopUpService { private popUp: Window | null = null; - private handle: number = -1; + private handle = -1; private readonly resultInternal$ = new Subject(); @@ -39,6 +39,7 @@ export class PopUpService { ); const windowIdentifier = this.windowInternal; + if (!windowIdentifier) { return false; } @@ -67,6 +68,7 @@ export class PopUpService { ); const windowIdentifier = this.windowInternal; + if (!windowIdentifier) { return; } @@ -118,6 +120,7 @@ export class PopUpService { sendMessageToMainWindow(url: string, config: OpenIdConfiguration): void { const windowIdentifier = this.windowInternal; + if (!windowIdentifier) { return; } @@ -131,6 +134,7 @@ export class PopUpService { private cleanUp(listener: any, config: OpenIdConfiguration): void { const windowIdentifier = this.windowInternal; + if (!windowIdentifier) { return; } @@ -151,6 +155,7 @@ export class PopUpService { config: OpenIdConfiguration ): void { const windowIdentifier = this.windowInternal; + if (!windowIdentifier) { return; } @@ -179,6 +184,7 @@ export class PopUpService { ...(popupOptions || {}), }; const windowIdentifier = this.windowInternal; + if (!windowIdentifier) { return ''; } From 5452f5ae64fa85e550bf4bf72e8d59fbe91b11a2 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Sun, 15 Oct 2023 10:39:27 +0200 Subject: [PATCH 10/56] added more null checks --- .../src/lib/auth-state/check-auth.service.ts | 11 ++++++++++- .../src/lib/auto-login/auto-login.service.ts | 6 +++++- .../auth-well-known/auth-well-known.service.ts | 9 +++++++++ .../rules/ensure-no-duplicated-configs.rule.ts | 6 +++--- .../user-callback-handler.service.ts | 14 +++++++++++--- .../src/lib/flows/flows-data.service.ts | 6 +++++- .../src/lib/flows/reset-auth-data.service.ts | 6 +++++- .../src/lib/iframe/existing-iframe.service.ts | 4 ++-- .../src/lib/logging/logger.service.ts | 6 +++++- .../src/lib/login/login.service.ts | 9 ++++++++- .../lib/utils/flowHelper/flow-helper.service.ts | 6 +++++- 11 files changed, 68 insertions(+), 15 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.ts index e7bb9bc5..580b62cd 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.ts @@ -49,10 +49,19 @@ export class CheckAuthService { } checkAuth( - configuration: OpenIdConfiguration, + configuration: OpenIdConfiguration | null, allConfigs: OpenIdConfiguration[], url?: string ): Observable { + if (!configuration) { + return throwError( + () => + new Error( + 'Please provide a configuration before setting up the module' + ) + ); + } + this.publicEventsService.fireEvent(EventTypes.CheckingAuth); const stateParamFromUrl = diff --git a/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login.service.ts b/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login.service.ts index 5520c7ff..0ed139f5 100644 --- a/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login.service.ts @@ -30,7 +30,11 @@ export class AutoLoginService { * @param config The OpenId configuration. * @param url The redirect URL to save. */ - saveRedirectRoute(config: OpenIdConfiguration, url: string): void { + saveRedirectRoute(config: OpenIdConfiguration | null, url: string): void { + if (!config) { + return; + } + this.storageService.write(STORAGE_KEY, url, config); } diff --git a/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known.service.ts b/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known.service.ts index ca859274..d1cbc0d9 100644 --- a/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known.service.ts @@ -30,6 +30,15 @@ export class AuthWellKnownService { queryAndStoreAuthWellKnownEndPoints( config: OpenIdConfiguration ): Observable { + if (!config) { + return throwError( + () => + new Error( + 'Please provide a configuration before setting up the module' + ) + ); + } + const alreadySavedWellKnownEndpoints = this.storagePersistenceService.read( 'authWellKnownEndPoints', config diff --git a/projects/angular-auth-oidc-client/src/lib/config/validation/rules/ensure-no-duplicated-configs.rule.ts b/projects/angular-auth-oidc-client/src/lib/config/validation/rules/ensure-no-duplicated-configs.rule.ts index 41ceae5c..4f9b4e76 100644 --- a/projects/angular-auth-oidc-client/src/lib/config/validation/rules/ensure-no-duplicated-configs.rule.ts +++ b/projects/angular-auth-oidc-client/src/lib/config/validation/rules/ensure-no-duplicated-configs.rule.ts @@ -3,7 +3,7 @@ import { POSITIVE_VALIDATION_RESULT, RuleValidationResult } from '../rule'; const createIdentifierToCheck = (passedConfig: OpenIdConfiguration): string => { if (!passedConfig) { - return null; + return ''; } const { authority, clientId, scope } = passedConfig; @@ -19,9 +19,9 @@ export const ensureNoDuplicatedConfigsRule = ( ): RuleValidationResult => { const allIdentifiers = passedConfigs.map((x) => createIdentifierToCheck(x)); - const someAreNull = allIdentifiers.some((x) => x === null); + const someAreNotSet = allIdentifiers.some((x) => x === ''); - if (someAreNull) { + if (someAreNotSet) { return { result: false, messages: [ diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/user-callback-handler.service.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/user-callback-handler.service.ts index 622b8cef..5ca190d4 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/user-callback-handler.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/user-callback-handler.service.ts @@ -67,7 +67,7 @@ export class UserCallbackHandlerService { if (!!userData) { if (!refreshToken) { this.flowsDataService.setSessionState( - authResult.session_state, + authResult?.session_state, configuration ); } @@ -99,9 +99,13 @@ export class UserCallbackHandlerService { } private publishAuthState( - stateValidationResult: StateValidationResult, + stateValidationResult: StateValidationResult | null, isRenewProcess: boolean ): void { + if (!stateValidationResult) { + return; + } + this.authStateService.updateAndPublishAuthState({ isAuthenticated: true, validationResult: stateValidationResult.state, @@ -110,9 +114,13 @@ export class UserCallbackHandlerService { } private publishUnauthenticatedState( - stateValidationResult: StateValidationResult, + stateValidationResult: StateValidationResult | null, isRenewProcess: boolean ): void { + if (!stateValidationResult) { + return; + } + this.authStateService.updateAndPublishAuthState({ isAuthenticated: false, validationResult: stateValidationResult.state, diff --git a/projects/angular-auth-oidc-client/src/lib/flows/flows-data.service.ts b/projects/angular-auth-oidc-client/src/lib/flows/flows-data.service.ts index 9e8b4980..b765e885 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/flows-data.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/flows-data.service.ts @@ -162,7 +162,11 @@ export class FlowsDataService { ); } - resetSilentRenewRunning(configuration: OpenIdConfiguration): void { + resetSilentRenewRunning(configuration: OpenIdConfiguration | null): void { + if (!configuration) { + return; + } + this.storagePersistenceService.write( 'storageSilentRenewRunning', '', diff --git a/projects/angular-auth-oidc-client/src/lib/flows/reset-auth-data.service.ts b/projects/angular-auth-oidc-client/src/lib/flows/reset-auth-data.service.ts index 27d476e8..d43c9fdc 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/reset-auth-data.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/reset-auth-data.service.ts @@ -15,9 +15,13 @@ export class ResetAuthDataService { ) {} resetAuthorizationData( - currentConfiguration: OpenIdConfiguration, + currentConfiguration: OpenIdConfiguration | null, allConfigs: OpenIdConfiguration[] ): void { + if (!currentConfiguration) { + return; + } + this.userService.resetUserDataInStore(currentConfiguration, allConfigs); this.flowsDataService.resetStorageFlowData(currentConfiguration); this.authStateService.setUnauthenticatedAndFireEvent( diff --git a/projects/angular-auth-oidc-client/src/lib/iframe/existing-iframe.service.ts b/projects/angular-auth-oidc-client/src/lib/iframe/existing-iframe.service.ts index 1f805345..bf6f74f4 100644 --- a/projects/angular-auth-oidc-client/src/lib/iframe/existing-iframe.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/iframe/existing-iframe.service.ts @@ -46,7 +46,7 @@ export class IFrameService { ): HTMLIFrameElement | null { try { const iFrameElement = - this.document.defaultView.parent.document.getElementById(identifier); + this.document.defaultView?.parent.document.getElementById(identifier); if (this.isIFrameElement(iFrameElement)) { return iFrameElement; @@ -69,7 +69,7 @@ export class IFrameService { } private isIFrameElement( - element: HTMLElement | null + element: HTMLElement | null | undefined ): element is HTMLIFrameElement { return !!element && element instanceof HTMLIFrameElement; } diff --git a/projects/angular-auth-oidc-client/src/lib/logging/logger.service.ts b/projects/angular-auth-oidc-client/src/lib/logging/logger.service.ts index 27adc32a..0428b286 100644 --- a/projects/angular-auth-oidc-client/src/lib/logging/logger.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/logging/logger.service.ts @@ -70,10 +70,14 @@ export class LoggerService { } logDebug( - configuration: OpenIdConfiguration, + configuration: OpenIdConfiguration | null, message: any, ...args: any[] ): void { + if (!configuration) { + return; + } + if (!this.logLevelIsSet(configuration)) { return; } diff --git a/projects/angular-auth-oidc-client/src/lib/login/login.service.ts b/projects/angular-auth-oidc-client/src/lib/login/login.service.ts index 601148b3..37020be2 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/login.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/login.service.ts @@ -20,7 +20,14 @@ export class LoginService { private readonly popupService: PopUpService ) {} - login(configuration: OpenIdConfiguration, authOptions?: AuthOptions): void { + login( + configuration: OpenIdConfiguration | null, + authOptions?: AuthOptions + ): void { + if (!configuration) { + return; + } + const { usePushedAuthorisationRequests } = configuration; if (authOptions?.customParams) { diff --git a/projects/angular-auth-oidc-client/src/lib/utils/flowHelper/flow-helper.service.ts b/projects/angular-auth-oidc-client/src/lib/utils/flowHelper/flow-helper.service.ts index 01d8ce94..01920832 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/flowHelper/flow-helper.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/flowHelper/flow-helper.service.ts @@ -15,8 +15,12 @@ export class FlowHelper { } isCurrentFlowCodeFlowWithRefreshTokens( - configuration: OpenIdConfiguration + configuration: OpenIdConfiguration | null ): boolean { + if (!configuration) { + return false; + } + const { useRefreshToken } = configuration; return ( From 148ed4a48909faf9f198f2904ab9bec3c1653825 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Sun, 15 Oct 2023 12:54:14 +0200 Subject: [PATCH 11/56] Foxed more errors --- .../src/lib/auth-state/auth-state.service.ts | 39 +++++++++++++--- .../src/lib/auth-state/check-auth.service.ts | 11 ++++- .../lib/callback/refresh-session.service.ts | 11 ++++- .../auth-well-known.service.ts | 2 +- .../src/lib/flows/flows-data.service.ts | 12 ++++- .../src/lib/login/login.service.ts | 20 +++++++- .../logoff-revocation.service.ts | 46 +++++++++++++++++-- .../src/lib/oidc.security.service.ts | 2 +- .../src/lib/user-data/user.service.ts | 11 ++++- .../utils/tokenHelper/token-helper.service.ts | 6 ++- .../src/lib/utils/url/url.service.ts | 6 ++- 11 files changed, 144 insertions(+), 22 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.ts index b25308a2..4556e538 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.ts @@ -1,5 +1,5 @@ import { Injectable } from '@angular/core'; -import { BehaviorSubject, Observable } from 'rxjs'; +import { BehaviorSubject, Observable, throwError } from 'rxjs'; import { distinctUntilChanged } from 'rxjs/operators'; import { OpenIdConfiguration } from '../config/openid-configuration'; import { AuthResult } from '../flows/callback-context'; @@ -78,7 +78,11 @@ export class AuthStateService { this.setAuthenticatedAndFireEvent(allConfigs); } - getAccessToken(configuration: OpenIdConfiguration): string { + getAccessToken(configuration: OpenIdConfiguration | null): string { + if (!configuration) { + return ''; + } + if (!this.isAuthenticated(configuration)) { return ''; } @@ -88,7 +92,11 @@ export class AuthStateService { return this.decodeURIComponentSafely(token); } - getIdToken(configuration: OpenIdConfiguration): string { + getIdToken(configuration: OpenIdConfiguration | null): string { + if (!configuration) { + return ''; + } + if (!this.isAuthenticated(configuration)) { return ''; } @@ -98,7 +106,11 @@ export class AuthStateService { return this.decodeURIComponentSafely(token); } - getRefreshToken(configuration: OpenIdConfiguration): string { + getRefreshToken(configuration: OpenIdConfiguration | null): string { + if (!configuration) { + return ''; + } + if (!this.isAuthenticated(configuration)) { return ''; } @@ -108,7 +120,11 @@ export class AuthStateService { return this.decodeURIComponentSafely(token); } - getAuthenticationResult(configuration: OpenIdConfiguration): any { + getAuthenticationResult(configuration: OpenIdConfiguration | null): any { + if (!configuration) { + return ''; + } + if (!this.isAuthenticated(configuration)) { return null; } @@ -213,7 +229,18 @@ export class AuthStateService { return hasExpired; } - isAuthenticated(configuration: OpenIdConfiguration): boolean { + isAuthenticated(configuration: OpenIdConfiguration | null): boolean { + if (!configuration) { + throwError( + () => + new Error( + 'Please provide a configuration before setting up the module' + ) + ); + + return false; + } + const hasAccessToken = !!this.storagePersistenceService.getAccessToken(configuration); const hasIdToken = diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.ts index 580b62cd..2a93cb56 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.ts @@ -114,9 +114,18 @@ export class CheckAuthService { } checkAuthIncludingServer( - configuration: OpenIdConfiguration, + configuration: OpenIdConfiguration | null, allConfigs: OpenIdConfiguration[] ): Observable { + if (!configuration) { + return throwError( + () => + new Error( + 'Please provide a configuration before setting up the module' + ) + ); + } + return this.checkAuthWithConfig(configuration, allConfigs).pipe( switchMap((loginResponse) => { const { isAuthenticated } = loginResponse; diff --git a/projects/angular-auth-oidc-client/src/lib/callback/refresh-session.service.ts b/projects/angular-auth-oidc-client/src/lib/callback/refresh-session.service.ts index 3ab47cfd..6728b2ce 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/refresh-session.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/refresh-session.service.ts @@ -47,10 +47,19 @@ export class RefreshSessionService { ) {} userForceRefreshSession( - config: OpenIdConfiguration, + config: OpenIdConfiguration | null, allConfigs: OpenIdConfiguration[], extraCustomParams?: { [key: string]: string | number | boolean } ): Observable { + if (!config) { + return throwError( + () => + new Error( + 'Please provide a configuration before setting up the module' + ) + ); + } + this.persistCustomParams(extraCustomParams, config); return this.forceRefreshSession(config, allConfigs, extraCustomParams); diff --git a/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known.service.ts b/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known.service.ts index d1cbc0d9..af861dad 100644 --- a/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known.service.ts @@ -28,7 +28,7 @@ export class AuthWellKnownService { } queryAndStoreAuthWellKnownEndPoints( - config: OpenIdConfiguration + config: OpenIdConfiguration | null ): Observable { if (!config) { return throwError( diff --git a/projects/angular-auth-oidc-client/src/lib/flows/flows-data.service.ts b/projects/angular-auth-oidc-client/src/lib/flows/flows-data.service.ts index b765e885..999c784b 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/flows-data.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/flows-data.service.ts @@ -26,7 +26,11 @@ export class FlowsDataService { this.storagePersistenceService.write('authNonce', nonce, configuration); } - getAuthStateControl(configuration: OpenIdConfiguration): any { + getAuthStateControl(configuration: OpenIdConfiguration | null): string { + if (!configuration) { + return ''; + } + return this.storagePersistenceService.read( 'authStateControl', configuration @@ -35,8 +39,12 @@ export class FlowsDataService { setAuthStateControl( authStateControl: string, - configuration: OpenIdConfiguration + configuration: OpenIdConfiguration | null ): boolean { + if (!configuration) { + return false; + } + return this.storagePersistenceService.write( 'authStateControl', authStateControl, diff --git a/projects/angular-auth-oidc-client/src/lib/login/login.service.ts b/projects/angular-auth-oidc-client/src/lib/login/login.service.ts index 37020be2..6d8d4059 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/login.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/login.service.ts @@ -1,5 +1,5 @@ import { Injectable } from '@angular/core'; -import { Observable, of } from 'rxjs'; +import { Observable, of, throwError } from 'rxjs'; import { AuthOptions } from '../auth-options'; import { OpenIdConfiguration } from '../config/openid-configuration'; import { StoragePersistenceService } from '../storage/storage-persistence.service'; @@ -25,6 +25,13 @@ export class LoginService { authOptions?: AuthOptions ): void { if (!configuration) { + throwError( + () => + new Error( + 'Please provide a configuration before setting up the module' + ) + ); + return; } @@ -49,11 +56,20 @@ export class LoginService { } loginWithPopUp( - configuration: OpenIdConfiguration, + configuration: OpenIdConfiguration | null, allConfigs: OpenIdConfiguration[], authOptions?: AuthOptions, popupOptions?: PopupOptions ): Observable { + if (!configuration) { + return throwError( + () => + new Error( + 'Please provide a configuration before setting up the module' + ) + ); + } + const isAlreadyInPopUp = this.popupService.isCurrentlyInPopup(configuration); diff --git a/projects/angular-auth-oidc-client/src/lib/logoff-revoke/logoff-revocation.service.ts b/projects/angular-auth-oidc-client/src/lib/logoff-revoke/logoff-revocation.service.ts index 769cb19a..ecface23 100644 --- a/projects/angular-auth-oidc-client/src/lib/logoff-revoke/logoff-revocation.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/logoff-revoke/logoff-revocation.service.ts @@ -28,10 +28,19 @@ export class LogoffRevocationService { // Logs out on the server and the local client. // If the server state has changed, check session, then only a local logout. logoff( - config: OpenIdConfiguration, + config: OpenIdConfiguration | null, allConfigs: OpenIdConfiguration[], logoutAuthOptions?: LogoutAuthOptions ): Observable { + if (!config) { + return throwError( + () => + new Error( + 'Please provide a configuration before setting up the module' + ) + ); + } + this.loggerService.logDebug( config, 'logoff, remove auth', @@ -83,7 +92,7 @@ export class LogoffRevocationService { } logoffLocal( - config: OpenIdConfiguration, + config: OpenIdConfiguration | null, allConfigs: OpenIdConfiguration[] ): void { this.resetAuthDataService.resetAuthorizationData(config, allConfigs); @@ -99,10 +108,19 @@ export class LogoffRevocationService { // The refresh token and and the access token are revoked on the server. If the refresh token does not exist // only the access token is revoked. Then the logout run. logoffAndRevokeTokens( - config: OpenIdConfiguration, + config: OpenIdConfiguration | null, allConfigs: OpenIdConfiguration[], logoutAuthOptions?: LogoutAuthOptions ): Observable { + if (!config) { + return throwError( + () => + new Error( + 'Please provide a configuration before setting up the module' + ) + ); + } + const { revocationEndpoint } = this.storagePersistenceService.read('authWellKnownEndPoints', config) || {}; @@ -144,9 +162,18 @@ export class LogoffRevocationService { // the storage is revoked. You can pass any token to revoke. This makes it possible to // manage your own tokens. The is a public API. revokeAccessToken( - configuration: OpenIdConfiguration, + configuration: OpenIdConfiguration | null, accessToken?: any ): Observable { + if (!configuration) { + return throwError( + () => + new Error( + 'Please provide a configuration before setting up the module' + ) + ); + } + const accessTok = accessToken || this.storagePersistenceService.getAccessToken(configuration); @@ -163,9 +190,18 @@ export class LogoffRevocationService { // If no token is provided, then the token from the storage is revoked. You can pass any token to revoke. // This makes it possible to manage your own tokens. revokeRefreshToken( - configuration: OpenIdConfiguration, + configuration: OpenIdConfiguration | null, refreshToken?: any ): Observable { + if (!configuration) { + return throwError( + () => + new Error( + 'Please provide a configuration before setting up the module' + ) + ); + } + const refreshTok = refreshToken || this.storagePersistenceService.getRefreshToken(configuration); diff --git a/projects/angular-auth-oidc-client/src/lib/oidc.security.service.ts b/projects/angular-auth-oidc-client/src/lib/oidc.security.service.ts index 977f01d4..603a1b74 100644 --- a/projects/angular-auth-oidc-client/src/lib/oidc.security.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/oidc.security.service.ts @@ -104,7 +104,7 @@ export class OidcSecurityService { * * @param configId The configId to identify the config. If not passed, the first one is being returned */ - getConfiguration(configId?: string): Observable { + getConfiguration(configId?: string): Observable { return this.configurationService.getOpenIDConfiguration(configId); } diff --git a/projects/angular-auth-oidc-client/src/lib/user-data/user.service.ts b/projects/angular-auth-oidc-client/src/lib/user-data/user.service.ts index 1a5ea321..e44feadd 100644 --- a/projects/angular-auth-oidc-client/src/lib/user-data/user.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/user-data/user.service.ts @@ -108,7 +108,16 @@ export class UserService { return of(existingUserDataFromStorage); } - getUserDataFromStore(currentConfiguration: OpenIdConfiguration): any { + getUserDataFromStore(currentConfiguration: OpenIdConfiguration | null): any { + if (!currentConfiguration) { + return throwError( + () => + new Error( + 'Please provide a configuration before setting up the module' + ) + ); + } + return ( this.storagePersistenceService.read('userData', currentConfiguration) || null diff --git a/projects/angular-auth-oidc-client/src/lib/utils/tokenHelper/token-helper.service.ts b/projects/angular-auth-oidc-client/src/lib/utils/tokenHelper/token-helper.service.ts index 1d23f5be..acd67732 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/tokenHelper/token-helper.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/tokenHelper/token-helper.service.ts @@ -62,8 +62,12 @@ export class TokenHelperService { getPayloadFromToken( token: any, encoded: boolean, - configuration: OpenIdConfiguration + configuration: OpenIdConfiguration | null ): any { + if (!configuration) { + return {}; + } + if (!this.tokenIsValid(token, configuration)) { return {}; } diff --git a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts index c1037e6e..e10dd710 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts @@ -152,9 +152,13 @@ export class UrlService { } getEndSessionUrl( - configuration: OpenIdConfiguration, + configuration: OpenIdConfiguration | null, customParams?: { [p: string]: string | number | boolean } ): string | null { + if (!configuration) { + return null; + } + const idToken = this.storagePersistenceService.getIdToken(configuration); const { customParamsEndSessionRequest } = configuration; const mergedParams = { ...customParamsEndSessionRequest, ...customParams }; From ea41b50a93fb9a451abd940b5df5b5d41fa752bd Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Sun, 15 Oct 2023 13:38:22 +0200 Subject: [PATCH 12/56] added strict mode --- .../lib/callback/refresh-session.service.ts | 53 +++++++++---------- 1 file changed, 24 insertions(+), 29 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/callback/refresh-session.service.ts b/projects/angular-auth-oidc-client/src/lib/callback/refresh-session.service.ts index 6728b2ce..b4e42f65 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/refresh-session.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/refresh-session.service.ts @@ -112,7 +112,30 @@ export class RefreshSessionService { this.silentRenewService.refreshSessionWithIFrameCompleted$.pipe(take(1)), ]).pipe( timeout(timeOutTime), - retryWhen(this.timeoutRetryStrategy.bind(this)), + retryWhen((errors) => { + return errors.pipe( + mergeMap((error, index) => { + const scalingDuration = 1000; + const currentAttempt = index + 1; + + if ( + !(error instanceof TimeoutError) || + currentAttempt > MAX_RETRY_ATTEMPTS + ) { + return throwError(() => new Error(error)); + } + + this.loggerService.logDebug( + config, + `forceRefreshSession timeout. Attempt #${currentAttempt}` + ); + + this.flowsDataService.resetSilentRenewRunning(config); + + return timer(currentAttempt * scalingDuration); + }) + ); + }), map(([_, callbackContext]) => { const isAuthenticated = this.authStateService.areAuthStorageTokensValid(config); @@ -203,32 +226,4 @@ export class RefreshSessionService { }) ); } - - private timeoutRetryStrategy( - errorAttempts: Observable, - config: OpenIdConfiguration - ): Observable { - return errorAttempts.pipe( - mergeMap((error, index) => { - const scalingDuration = 1000; - const currentAttempt = index + 1; - - if ( - !(error instanceof TimeoutError) || - currentAttempt > MAX_RETRY_ATTEMPTS - ) { - return throwError(() => new Error(error)); - } - - this.loggerService.logDebug( - config, - `forceRefreshSession timeout. Attempt #${currentAttempt}` - ); - - this.flowsDataService.resetSilentRenewRunning(config); - - return timer(currentAttempt * scalingDuration); - }) - ); - } } From f1d14271b353ed47cff1d7a97fe621b4a306251a Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Wed, 3 Jan 2024 18:08:58 +0100 Subject: [PATCH 13/56] Update code formatting and type annotations --- .vscode/settings.json | 4 ++-- .../src/lib/utils/url/url.service.spec.ts | 4 ++-- .../src/lib/validation/state-validation.service.spec.ts | 7 ++++--- .../src/lib/validation/token-validation.service.spec.ts | 8 +++++--- projects/angular-auth-oidc-client/src/test/auto-mock.ts | 3 ++- 5 files changed, 15 insertions(+), 11 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index f90fafa0..0265e7ba 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,7 +1,7 @@ { "editor.codeActionsOnSave": { - "source.organizeImports": true, - "source.fixAll.eslint": true + "source.organizeImports": "explicit", + "source.fixAll.eslint": "explicit" }, "editor.formatOnSave": true, "editor.formatOnPaste": true, diff --git a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.spec.ts index 49e7434f..1d0ebbb0 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.spec.ts @@ -1711,7 +1711,7 @@ describe('UrlService Tests', () => { const resultObs$ = serviceAsAny.createUrlCodeFlowAuthorize(config); - resultObs$.subscribe((result) => { + resultObs$.subscribe((result: any) => { expect(result).toBe( `authorizationEndpoint?client_id=clientId&redirect_uri=http%3A%2F%2Fany-url.com&response_type=${responseType}&scope=${scope}&nonce=${nonce}&state=${state}` ); @@ -1759,7 +1759,7 @@ describe('UrlService Tests', () => { customParams: { to: 'add', as: 'well' }, }); - resultObs$.subscribe((result) => { + resultObs$.subscribe((result: any) => { expect(result).toBe( `authorizationEndpoint?client_id=clientId&redirect_uri=http%3A%2F%2Fany-url.com` + `&response_type=${responseType}&scope=${scope}&nonce=${nonce}&state=${state}&to=add&as=well` diff --git a/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.spec.ts index fcb4cacb..04585714 100644 --- a/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.spec.ts @@ -3,6 +3,7 @@ import { of } from 'rxjs'; import { mockClass } from '../../test/auto-mock'; import { AuthWellKnownEndpoints } from '../config/auth-well-known/auth-well-known-endpoints'; import { OpenIdConfiguration } from '../config/openid-configuration'; +import { CallbackContext } from '../flows/callback-context'; import { LogLevel } from '../logging/log-level'; import { LoggerService } from '../logging/logger.service'; import { StoragePersistenceService } from '../storage/storage-persistence.service'; @@ -2101,12 +2102,12 @@ describe('State Validation Service', () => { config.maxIdTokenIatOffsetAllowedInSeconds = 0; config.disableIdTokenValidation = true; - const callbackContext = { + const callbackContext: CallbackContext = { code: 'fdffsdfsdf', - refreshToken: null, + refreshToken: '', state: 'fdffsggggggdfsdf', sessionState: 'fdffsggggggdfsdf', - existingIdToken: null, + existingIdToken: '', authResult: {}, isRenewProcess: false, jwtKeys: null, diff --git a/projects/angular-auth-oidc-client/src/lib/validation/token-validation.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/validation/token-validation.service.spec.ts index 573de2fb..f83b7e15 100644 --- a/projects/angular-auth-oidc-client/src/lib/validation/token-validation.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/validation/token-validation.service.spec.ts @@ -518,7 +518,7 @@ describe('TokenValidationService', () => { it('returns true if no idToken is passed', waitForAsync(() => { const valueFalse$ = tokenValidationService.validateSignatureIdToken( - null, + null as any, 'some-jwt-keys', { configId: 'configId1' } ); @@ -776,7 +776,9 @@ describe('TokenValidationService', () => { describe('validateIdTokenExpNotExpired', () => { it('returns false when getTokenExpirationDate returns null', () => { - spyOn(tokenHelperService, 'getTokenExpirationDate').and.returnValue(null); + spyOn(tokenHelperService, 'getTokenExpirationDate').and.returnValue( + null as unknown as Date + ); const notExpired = tokenValidationService.validateIdTokenExpNotExpired( 'idToken', { configId: 'configId1' }, @@ -824,7 +826,7 @@ describe('TokenValidationService', () => { testCases.forEach(({ date, offsetSeconds, expectedResult }) => { it(`returns ${expectedResult} if ${date} is given with an offset of ${offsetSeconds}`, () => { const notExpired = tokenValidationService.validateAccessTokenNotExpired( - date, + date as Date, { configId: 'configId1' }, offsetSeconds ); diff --git a/projects/angular-auth-oidc-client/src/test/auto-mock.ts b/projects/angular-auth-oidc-client/src/test/auto-mock.ts index 5bae495a..956e8dd9 100644 --- a/projects/angular-auth-oidc-client/src/test/auto-mock.ts +++ b/projects/angular-auth-oidc-client/src/test/auto-mock.ts @@ -13,7 +13,8 @@ export function mockClass(obj: new (...args: any[]) => T): any { allMethods.forEach( // eslint-disable-next-line @typescript-eslint/no-empty-function - (method) => (mockedClass.prototype[method] = (): void => {}) + (method: string) => + ((mockedClass.prototype as any)[method] = (): void => {}) ); allProperties.forEach((method) => { From 075cfe6407768f9875316f40a9cf6ef91c003941 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Thu, 4 Jan 2024 07:19:11 +0100 Subject: [PATCH 14/56] Fix login service and flows service callback return types --- .../src/lib/flows/flows.service.spec.ts | 36 ++++++++-------- .../src/lib/login/login.service.spec.ts | 14 +++---- .../src/lib/utils/url/url.service.spec.ts | 42 +++++++++---------- .../state-validation.service.spec.ts | 40 +++++++++--------- 4 files changed, 66 insertions(+), 66 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/flows/flows.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/flows.service.spec.ts index 5e0500d3..c79a0f79 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/flows.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/flows.service.spec.ts @@ -89,23 +89,23 @@ describe('Flows Service', () => { const codeFlowCallbackSpy = spyOn( codeFlowCallbackHandlerService, 'codeFlowCallback' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const codeFlowCodeRequestSpy = spyOn( codeFlowCallbackHandlerService, 'codeFlowCodeRequest' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const callbackHistoryAndResetJwtKeysSpy = spyOn( historyJwtKeysCallbackHandlerService, 'callbackHistoryAndResetJwtKeys' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const callbackStateValidationSpy = spyOn( stateValidationCallbackHandlerService, 'callbackStateValidation' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const callbackUserSpy = spyOn( userCallbackHandlerService, 'callbackUser' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const allConfigs = [ { configId: 'configId1', @@ -133,19 +133,19 @@ describe('Flows Service', () => { const codeFlowCodeRequestSpy = spyOn( codeFlowCallbackHandlerService, 'codeFlowCodeRequest' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const callbackHistoryAndResetJwtKeysSpy = spyOn( historyJwtKeysCallbackHandlerService, 'callbackHistoryAndResetJwtKeys' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const callbackStateValidationSpy = spyOn( stateValidationCallbackHandlerService, 'callbackStateValidation' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const callbackUserSpy = spyOn( userCallbackHandlerService, 'callbackUser' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const allConfigs = [ { configId: 'configId1', @@ -173,19 +173,19 @@ describe('Flows Service', () => { const implicitFlowCallbackSpy = spyOn( implicitFlowCallbackHandlerService, 'implicitFlowCallback' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const callbackHistoryAndResetJwtKeysSpy = spyOn( historyJwtKeysCallbackHandlerService, 'callbackHistoryAndResetJwtKeys' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const callbackStateValidationSpy = spyOn( stateValidationCallbackHandlerService, 'callbackStateValidation' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const callbackUserSpy = spyOn( userCallbackHandlerService, 'callbackUser' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const allConfigs = [ { configId: 'configId1', @@ -209,23 +209,23 @@ describe('Flows Service', () => { const refreshSessionWithRefreshTokensSpy = spyOn( refreshSessionCallbackHandlerService, 'refreshSessionWithRefreshTokens' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const refreshTokensRequestTokensSpy = spyOn( refreshTokenCallbackHandlerService, 'refreshTokensRequestTokens' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const callbackHistoryAndResetJwtKeysSpy = spyOn( historyJwtKeysCallbackHandlerService, 'callbackHistoryAndResetJwtKeys' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const callbackStateValidationSpy = spyOn( stateValidationCallbackHandlerService, 'callbackStateValidation' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const callbackUserSpy = spyOn( userCallbackHandlerService, 'callbackUser' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const allConfigs = [ { configId: 'configId1', diff --git a/projects/angular-auth-oidc-client/src/lib/login/login.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/login.service.spec.ts index 32ea683b..df1d23b9 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/login.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/login.service.spec.ts @@ -99,11 +99,11 @@ describe('LoginService', () => { const loginWithPopUpPar = spyOn( parLoginService, 'loginWithPopUpPar' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as LoginResponse)); const loginWithPopUpStandardSpy = spyOn( popUpLoginService, 'loginWithPopUpStandard' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as LoginResponse)); // act service.loginWithPopUp(config, [config]).subscribe(() => { @@ -119,11 +119,11 @@ describe('LoginService', () => { const loginWithPopUpPar = spyOn( parLoginService, 'loginWithPopUpPar' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as LoginResponse)); const loginWithPopUpStandardSpy = spyOn( popUpLoginService, 'loginWithPopUpStandard' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as LoginResponse)); // act service.loginWithPopUp(config, [config]).subscribe(() => { @@ -143,7 +143,7 @@ describe('LoginService', () => { const authOptions = { customParams: { custom: 'params' } }; spyOn(popUpLoginService, 'loginWithPopUpStandard').and.returnValue( - of(null) + of({} as LoginResponse) ); // act @@ -164,11 +164,11 @@ describe('LoginService', () => { const loginWithPopUpPar = spyOn( parLoginService, 'loginWithPopUpPar' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as LoginResponse)); const loginWithPopUpStandardSpy = spyOn( popUpLoginService, 'loginWithPopUpStandard' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as LoginResponse)); spyOn(popUpService, 'isCurrentlyInPopup').and.returnValue(true); diff --git a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.spec.ts index 1d0ebbb0..866c4343 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.spec.ts @@ -194,7 +194,7 @@ describe('UrlService Tests', () => { }); it('returns null when clientId is null', () => { - const config = { configId: 'configId1', clientId: null }; + const config = { configId: 'configId1', clientId: '' }; const authorizationEndpoint = 'authorizationEndpoint'; spyOn(storagePersistenceService, 'read') @@ -218,7 +218,7 @@ describe('UrlService Tests', () => { const config = { configId: 'configId1', clientId: 'something', - responseType: null, + responseType: undefined, }; const authorizationEndpoint = 'authorizationEndpoint'; @@ -244,7 +244,7 @@ describe('UrlService Tests', () => { configId: 'configId1', clientId: 'something', responseType: 'responsetype', - scope: null, + scope: undefined, }; const authorizationEndpoint = 'authorizationEndpoint'; @@ -563,7 +563,7 @@ describe('UrlService Tests', () => { '188968487735-b1hh7k87nkkh6vv84548sinju2kpr7gn.apps.googleusercontent.com', responseType: 'id_token token', scope: 'openid email profile', - customParamsAuthRequest: null, + customParamsAuthRequest: undefined, configId: 'configId1', }; @@ -786,7 +786,7 @@ describe('UrlService Tests', () => { it('createRevocationEndpointBodyAccessToken returns null when no clientId is given', () => { const config = { authority: 'https://localhost:5001', - clientId: null, + clientId: '', } as OpenIdConfiguration; const value = service.createRevocationEndpointBodyAccessToken( 'mytoken', @@ -831,7 +831,7 @@ describe('UrlService Tests', () => { it('createRevocationEndpointBodyRefreshToken returns null when no clientId is given', () => { const config = { authority: 'https://localhost:5001', - clientId: null, + clientId: undefined, } as OpenIdConfiguration; const value = service.createRevocationEndpointBodyRefreshToken( 'mytoken', @@ -964,8 +964,8 @@ describe('UrlService Tests', () => { clientId: 'some-clientId', responseType: 'testResponseType', scope: 'testScope', - hdParam: null, - customParamsAuthRequest: null, + hdParam: undefined, + customParamsAuthRequest: undefined, } as OpenIdConfiguration; const authorizationEndpoint = 'authorizationEndpoint'; @@ -1073,7 +1073,7 @@ describe('UrlService Tests', () => { const codeVerifier = 'codeverifier'; spyOn(flowsDataService, 'getCodeVerifier').and.returnValue(codeVerifier); - const clientId = null; + const clientId = ''; const result = service.createBodyForCodeFlowCodeRequest( 'notRelevantParam', { clientId } @@ -1085,7 +1085,7 @@ describe('UrlService Tests', () => { it('returns null if silentrenewRunning is false and redirectUrl is falsy', () => { const codeVerifier = 'codeverifier'; const code = 'code'; - const redirectUrl = null; + const redirectUrl = ''; const clientId = 'clientId'; spyOn(flowsDataService, 'getCodeVerifier').and.returnValue(codeVerifier); @@ -1237,8 +1237,8 @@ describe('UrlService Tests', () => { clientId: 'testClientId', responseType: 'testResponseType', scope: 'testScope', - hdParam: null, - customParamsAuthRequest: null, + hdParam: undefined, + customParamsAuthRequest: undefined, redirectUrl: 'testRedirectUrl', }; @@ -1269,7 +1269,7 @@ describe('UrlService Tests', () => { responseType: 'testResponseType', scope: 'testScope', hdParam: 'testHdParam', - customParamsAuthRequest: null, + customParamsAuthRequest: undefined, redirectUrl: 'testRedirectUrl', }; @@ -1478,7 +1478,7 @@ describe('UrlService Tests', () => { const resultObs$ = serviceAsAny.createUrlCodeFlowWithSilentRenew(config); - resultObs$.subscribe((result) => { + resultObs$.subscribe((result: any) => { expect(result).toBe(''); }); })); @@ -1520,7 +1520,7 @@ describe('UrlService Tests', () => { const resultObs$ = serviceAsAny.createUrlCodeFlowWithSilentRenew(config); - resultObs$.subscribe((result) => { + resultObs$.subscribe((result: any) => { expect(result).toBe( `authorizationEndpoint?client_id=${clientId}&redirect_uri=http%3A%2F%2Fany-url.com&response_type=${responseType}&scope=${scope}&nonce=${nonce}&state=${state}&prompt=none` ); @@ -1560,7 +1560,7 @@ describe('UrlService Tests', () => { const resultObs$ = serviceAsAny.createUrlCodeFlowWithSilentRenew(config); - resultObs$.subscribe((result) => { + resultObs$.subscribe((result: any) => { expect(result).toBe(null); }); })); @@ -1670,7 +1670,7 @@ describe('UrlService Tests', () => { const resultObs$ = serviceAsAny.createUrlCodeFlowAuthorize(config); - resultObs$.subscribe((result) => { + resultObs$.subscribe((result: any) => { expect(result).toBeNull(); }); })); @@ -1796,7 +1796,7 @@ describe('UrlService Tests', () => { const resultObs$ = serviceAsAny.createUrlCodeFlowAuthorize(config); - resultObs$.subscribe((result) => { + resultObs$.subscribe((result: any) => { expect(result).toBe(''); }); })); @@ -1832,7 +1832,7 @@ describe('UrlService Tests', () => { postLogoutRedirectUri: 'https://localhost:44386/Unauthorized', } as OpenIdConfiguration; - spyOn(storagePersistenceService, 'getIdToken').and.returnValue(null); + spyOn(storagePersistenceService, 'getIdToken').and.returnValue(''); spyOn(storagePersistenceService, 'read') .withArgs('authWellKnownEndPoints', config) .and.returnValue({ @@ -1903,7 +1903,7 @@ describe('UrlService Tests', () => { it('create URL without postLogoutRedirectUri when not given', () => { const config = { - postLogoutRedirectUri: null, + postLogoutRedirectUri: '', } as OpenIdConfiguration; spyOn(storagePersistenceService, 'read') @@ -1980,7 +1980,7 @@ describe('UrlService Tests', () => { }); it('returns null if configurationProvider.openIDConfiguration has no clientId', () => { - const config = { clientId: null }; + const config = { clientId: '' } as OpenIdConfiguration; spyOn(storagePersistenceService, 'read') .withArgs('authWellKnownEndPoints', config) diff --git a/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.spec.ts index 04585714..250cb2ed 100644 --- a/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.spec.ts @@ -699,7 +699,7 @@ describe('State Validation Service', () => { describe('getValidatedStateResult', () => { it('should return authResponseIsValid false when null is passed', waitForAsync(() => { const isValidObs$ = stateValidationService.getValidatedStateResult( - null, + {} as CallbackContext, config ); @@ -723,7 +723,7 @@ describe('State Validation Service', () => { const callbackContext = { code: 'fdffsdfsdf', - refreshToken: null, + refreshToken: '', state: 'fdffsggggggdfsdf', sessionState: 'fdffsggggggdfsdf', existingIdToken: null, @@ -810,7 +810,7 @@ describe('State Validation Service', () => { const callbackContext = { code: 'fdffsdfsdf', - refreshToken: null, + refreshToken: '', state: 'fdffsdfhhhhsdf', sessionState: 'fdffsggggggdfsdf', authResult: { @@ -859,7 +859,7 @@ describe('State Validation Service', () => { const callbackContext = { code: 'fdffsdfsdf', - refreshToken: null, + refreshToken: '', state: 'fdffsdfhhhhsdf', sessionState: 'fdffsggggggdfsdf', authResult: { @@ -952,7 +952,7 @@ describe('State Validation Service', () => { const callbackContext = { code: 'fdffsdfsdf', - refreshToken: null, + refreshToken: '', state: 'fdffsdfhhhhsdf', sessionState: 'fdffsggggggdfsdf', authResult: { @@ -1004,7 +1004,7 @@ describe('State Validation Service', () => { const callbackContext = { code: 'fdffsdfsdf', - refreshToken: null, + refreshToken: '', state: 'fdffsdfhhhhsdf', sessionState: 'fdffsggggggdfsdf', authResult: { @@ -1066,7 +1066,7 @@ describe('State Validation Service', () => { const callbackContext = { code: 'fdffsdfsdf', - refreshToken: null, + refreshToken: '', state: 'fdffsdfhhhhsdf', sessionState: 'fdffsggggggdfsdf', authResult: { @@ -1133,7 +1133,7 @@ describe('State Validation Service', () => { const callbackContext = { code: 'fdffsdfsdf', - refreshToken: null, + refreshToken: '', state: 'fdffsdfhhhhsdf', sessionState: 'fdffsggggggdfsdf', authResult: { @@ -1207,7 +1207,7 @@ describe('State Validation Service', () => { const callbackContext = { code: 'fdffsdfsdf', - refreshToken: null, + refreshToken: '', state: 'fdffsdfhhhhsdf', sessionState: 'fdffsggggggdfsdf', authResult: { @@ -1284,7 +1284,7 @@ describe('State Validation Service', () => { const callbackContext = { code: 'fdffsdfsdf', - refreshToken: null, + refreshToken: '', state: 'fdffsdfhhhhsdf', sessionState: 'fdffsggggggdfsdf', authResult: { @@ -1349,7 +1349,7 @@ describe('State Validation Service', () => { const callbackContext = { code: 'fdffsdfsdf', - refreshToken: null, + refreshToken: '', state: 'fdffsdfhhhhsdf', sessionState: 'fdffsggggggdfsdf', authResult: { @@ -1424,7 +1424,7 @@ describe('State Validation Service', () => { const callbackContext = { code: 'fdffsdfsdf', - refreshToken: null, + refreshToken: '', state: 'fdffsdfhhhhsdf', sessionState: 'fdffsggggggdfsdf', authResult: { @@ -1499,7 +1499,7 @@ describe('State Validation Service', () => { const callbackContext = { code: 'fdffsdfsdf', - refreshToken: null, + refreshToken: '', state: 'fdffsdfhhhhsdf', sessionState: 'fdffsggggggdfsdf', authResult: { @@ -1578,7 +1578,7 @@ describe('State Validation Service', () => { const callbackContext = { code: 'fdffsdfsdf', - refreshToken: null, + refreshToken: '', state: 'fdffsdfhhhhsdf', sessionState: 'fdffsggggggdfsdf', authResult: { @@ -1661,7 +1661,7 @@ describe('State Validation Service', () => { const callbackContext = { code: 'fdffsdfsdf', - refreshToken: null, + refreshToken: '', state: 'fdffsdfhhhhsdf', sessionState: 'fdffsggggggdfsdf', authResult: { @@ -1755,7 +1755,7 @@ describe('State Validation Service', () => { const callbackContext = { code: 'fdffsdfsdf', - refreshToken: null, + refreshToken: '', state: 'fdffsdfhhhhsdf', sessionState: 'fdffsggggggdfsdf', authResult: { @@ -1853,7 +1853,7 @@ describe('State Validation Service', () => { const callbackContext = { code: 'fdffsdfsdf', - refreshToken: null, + refreshToken: '', state: 'fdffsdfhhhhsdf', sessionState: 'fdffsggggggdfsdf', authResult: { @@ -1944,7 +1944,7 @@ describe('State Validation Service', () => { const callbackContext = { code: 'fdffsdfsdf', - refreshToken: null, + refreshToken: '', state: 'fdffsdfhhhhsdf', sessionState: 'fdffsggggggdfsdf', authResult: { @@ -2023,7 +2023,7 @@ describe('State Validation Service', () => { const callbackContext = { code: 'fdffsdfsdf', - refreshToken: null, + refreshToken: '', state: 'fdffsdfhhhhsdf', sessionState: 'fdffsggggggdfsdf', authResult: { @@ -2066,7 +2066,7 @@ describe('State Validation Service', () => { const callbackContext = { code: 'fdffsdfsdf', - refreshToken: null, + refreshToken: '', state: 'fdffsggggggdfsdf', sessionState: 'fdffsggggggdfsdf', existingIdToken: null, From b1f73b507b1f5cbf3af53cca14d9f5ed4f0ee51c Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Thu, 4 Jan 2024 07:48:39 +0100 Subject: [PATCH 15/56] Fix various issues and improve code --- .../lib/auth-state/check-auth.service.spec.ts | 62 ++++++++++--------- .../auto-login-partial-routes.guard.spec.ts | 24 +++++-- .../src/lib/callback/callback.service.spec.ts | 9 +-- .../periodically-token-check.service.spec.ts | 8 +-- .../auth-well-known-data.service.spec.ts | 33 +++++----- .../auth-well-known-data.service.ts | 2 +- .../logoff-revocation.service.spec.ts | 8 +-- .../src/lib/oidc.security.service.spec.ts | 17 ++--- .../src/lib/oidc.security.service.ts | 2 +- .../src/lib/provide-auth.spec.ts | 2 +- .../storage/browser-storage.service.spec.ts | 2 +- .../storage-persistence.service.spec.ts | 2 +- .../src/lib/user-data/user-service.spec.ts | 10 +-- .../utils/equality/equality.service.spec.ts | 39 ++++-------- .../lib/utils/url/current-url.service.spec.ts | 2 +- .../src/lib/utils/url/url.service.spec.ts | 6 +- 16 files changed, 115 insertions(+), 113 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts index 4ac26f36..e42ef9e8 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts @@ -10,6 +10,8 @@ import { StsConfigLoader, StsConfigStaticLoader, } from '../config/loader/config-loader'; +import { OpenIdConfiguration } from '../config/openid-configuration'; +import { CallbackContext } from '../flows/callback-context'; import { CheckSessionService } from '../iframe/check-session.service'; import { SilentRenewService } from '../iframe/silent-renew.service'; import { LoggerService } from '../logging/logger.service'; @@ -103,7 +105,7 @@ describe('CheckAuthService', () => { }); afterEach(() => { - storagePersistenceService.clear(null); + storagePersistenceService.clear({} as OpenIdConfiguration); }); it('should create', () => { @@ -182,7 +184,7 @@ describe('CheckAuthService', () => { })); it('returns isAuthenticated: false with error message when config is not valid', waitForAsync(() => { - const allConfigs = []; + const allConfigs: OpenIdConfiguration[] = []; checkAuthService .checkAuth(allConfigs[0], allConfigs) @@ -191,7 +193,7 @@ describe('CheckAuthService', () => { isAuthenticated: false, errorMessage: 'Please provide at least one configuration before setting up the module', - configId: null, + configId: '', idToken: '', userData: null, accessToken: '', @@ -270,7 +272,7 @@ describe('CheckAuthService', () => { const spy = spyOn( callBackService, 'handleCallbackAndFireEvents' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); checkAuthService .checkAuth(allConfigs[0], allConfigs) @@ -278,9 +280,9 @@ describe('CheckAuthService', () => { expect(result).toEqual({ isAuthenticated: true, userData: undefined, - accessToken: undefined, + accessToken: '', configId: 'configId1', - idToken: undefined, + idToken: '', }); expect(spy).toHaveBeenCalled(); }); @@ -298,7 +300,7 @@ describe('CheckAuthService', () => { const spy = spyOn( callBackService, 'handleCallbackAndFireEvents' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); checkAuthService .checkAuth(allConfigs[0], allConfigs) @@ -306,9 +308,9 @@ describe('CheckAuthService', () => { expect(result).toEqual({ isAuthenticated: true, userData: undefined, - accessToken: undefined, + accessToken: '', configId: 'configId1', - idToken: undefined, + idToken: '', }); expect(spy).not.toHaveBeenCalled(); }); @@ -324,7 +326,7 @@ describe('CheckAuthService', () => { true ); spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( - of(null) + of({} as CallbackContext) ); const setAuthorizedAndFireEventSpy = spyOn( @@ -339,9 +341,9 @@ describe('CheckAuthService', () => { expect(result).toEqual({ isAuthenticated: true, userData: undefined, - accessToken: undefined, + accessToken: '', configId: 'configId1', - idToken: undefined, + idToken: '', }); expect(setAuthorizedAndFireEventSpy).toHaveBeenCalled(); expect(userServiceSpy).toHaveBeenCalled(); @@ -358,7 +360,7 @@ describe('CheckAuthService', () => { false ); spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( - of(null) + of({} as CallbackContext) ); const setAuthorizedAndFireEventSpy = spyOn( @@ -373,9 +375,9 @@ describe('CheckAuthService', () => { expect(result).toEqual({ isAuthenticated: false, userData: undefined, - accessToken: undefined, + accessToken: '', configId: 'configId1', - idToken: undefined, + idToken: '', }); expect(setAuthorizedAndFireEventSpy).not.toHaveBeenCalled(); expect(userServiceSpy).not.toHaveBeenCalled(); @@ -388,7 +390,7 @@ describe('CheckAuthService', () => { ]; spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( - of(null) + of({} as CallbackContext) ); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( true @@ -400,9 +402,9 @@ describe('CheckAuthService', () => { expect(result).toEqual({ isAuthenticated: true, userData: undefined, - accessToken: undefined, + accessToken: '', configId: 'configId1', - idToken: undefined, + idToken: '', }); }); })); @@ -413,7 +415,7 @@ describe('CheckAuthService', () => { ]; spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( - of(null) + of({} as CallbackContext) ); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( true @@ -432,7 +434,7 @@ describe('CheckAuthService', () => { ]; spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( - of(null) + of({} as CallbackContext) ); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( true @@ -453,7 +455,7 @@ describe('CheckAuthService', () => { const allConfigs = [config]; spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( - of(null) + of({} as CallbackContext) ); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( true @@ -475,7 +477,7 @@ describe('CheckAuthService', () => { ]; spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( - of(null) + of({} as CallbackContext) ); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( true @@ -496,7 +498,7 @@ describe('CheckAuthService', () => { ]; spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( - of(null) + of({} as CallbackContext) ); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( true @@ -517,7 +519,7 @@ describe('CheckAuthService', () => { ]; spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( - of(null) + of({} as CallbackContext) ); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( true @@ -536,7 +538,7 @@ describe('CheckAuthService', () => { ]; spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( - of(null) + of({} as CallbackContext) ); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( false @@ -589,7 +591,7 @@ describe('CheckAuthService', () => { ]; spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( - of(null) + of({} as CallbackContext) ); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( true @@ -617,7 +619,7 @@ describe('CheckAuthService', () => { false ); spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( - of(null) + of({} as CallbackContext) ); spyOn(refreshSessionService, 'forceRefreshSession').and.returnValue( @@ -647,7 +649,7 @@ describe('CheckAuthService', () => { false ); spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( - of(null) + of({} as CallbackContext) ); spyOn(checkSessionService, 'isCheckSessionConfigured').and.returnValue( true @@ -697,7 +699,7 @@ describe('CheckAuthService', () => { false ); spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( - of(null) + of({} as CallbackContext) ); spyOn(checkSessionService, 'isCheckSessionConfigured').and.returnValue( true @@ -840,7 +842,7 @@ describe('CheckAuthService', () => { 'the-state-param' ); - const allConfigs = []; + const allConfigs: OpenIdConfiguration[] = []; checkAuthService.checkAuthMultiple(allConfigs).subscribe({ error: (error) => { diff --git a/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-partial-routes.guard.spec.ts b/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-partial-routes.guard.spec.ts index 1225b8f7..1618f276 100644 --- a/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-partial-routes.guard.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-partial-routes.guard.spec.ts @@ -70,7 +70,7 @@ describe(`AutoLoginPartialRoutesGuard`, () => { }); afterEach(() => { - storagePersistenceService.clear(null); + storagePersistenceService.clear({}); }); it('should create', () => { @@ -93,7 +93,10 @@ describe(`AutoLoginPartialRoutesGuard`, () => { const loginSpy = spyOn(loginService, 'login'); guard - .canActivate(null, { url: 'some-url1' } as RouterStateSnapshot) + .canActivate( + {} as ActivatedRouteSnapshot, + { url: 'some-url1' } as RouterStateSnapshot + ) .subscribe(() => { expect(saveRedirectRouteSpy).toHaveBeenCalledOnceWith( { configId: 'configId1' }, @@ -157,7 +160,10 @@ describe(`AutoLoginPartialRoutesGuard`, () => { const loginSpy = spyOn(loginService, 'login'); guard - .canActivate(null, { url: 'some-url1' } as RouterStateSnapshot) + .canActivate( + {} as ActivatedRouteSnapshot, + { url: 'some-url1' } as RouterStateSnapshot + ) .subscribe(() => { expect(saveRedirectRouteSpy).not.toHaveBeenCalled(); expect(loginSpy).not.toHaveBeenCalled(); @@ -184,7 +190,10 @@ describe(`AutoLoginPartialRoutesGuard`, () => { const loginSpy = spyOn(loginService, 'login'); guard - .canActivateChild(null, { url: 'some-url1' } as RouterStateSnapshot) + .canActivateChild( + {} as ActivatedRouteSnapshot, + { url: 'some-url1' } as RouterStateSnapshot + ) .subscribe(() => { expect(saveRedirectRouteSpy).toHaveBeenCalledOnceWith( { configId: 'configId1' }, @@ -248,7 +257,10 @@ describe(`AutoLoginPartialRoutesGuard`, () => { const loginSpy = spyOn(loginService, 'login'); guard - .canActivateChild(null, { url: 'some-url1' } as RouterStateSnapshot) + .canActivateChild( + {} as ActivatedRouteSnapshot, + { url: 'some-url1' } as RouterStateSnapshot + ) .subscribe(() => { expect(saveRedirectRouteSpy).not.toHaveBeenCalled(); expect(loginSpy).not.toHaveBeenCalled(); @@ -368,7 +380,7 @@ describe(`AutoLoginPartialRoutesGuard`, () => { }); afterEach(() => { - storagePersistenceService.clear(null); + storagePersistenceService.clear({}); }); it('should save current route (empty) and call `login` if not authenticated already', waitForAsync(() => { diff --git a/projects/angular-auth-oidc-client/src/lib/callback/callback.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/callback/callback.service.spec.ts index 198eed33..44fd0ebd 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/callback.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/callback.service.spec.ts @@ -1,6 +1,7 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { Observable, of } from 'rxjs'; import { mockClass } from '../../test/auto-mock'; +import { CallbackContext } from '../flows/callback-context'; import { FlowHelper } from '../utils/flowHelper/flow-helper.service'; import { UrlService } from '../utils/url/url.service'; import { CallbackService } from './callback.service'; @@ -62,7 +63,7 @@ describe('CallbackService ', () => { const authorizedCallbackWithCodeSpy = spyOn( codeFlowCallbackService, 'authenticatedCallbackWithCode' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); callbackService .handleCallbackAndFireEvents('anyUrl', { configId: 'configId1' }, [ @@ -83,7 +84,7 @@ describe('CallbackService ', () => { const authorizedCallbackWithCodeSpy = spyOn( implicitFlowCallbackService, 'authenticatedImplicitFlowCallback' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); callbackService .handleCallbackAndFireEvents('anyUrl', { configId: 'configId1' }, [ @@ -103,7 +104,7 @@ describe('CallbackService ', () => { const authorizedCallbackWithCodeSpy = spyOn( implicitFlowCallbackService, 'authenticatedImplicitFlowCallback' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); callbackService .handleCallbackAndFireEvents( @@ -130,7 +131,7 @@ describe('CallbackService ', () => { const authenticatedCallbackWithCodeSpy = spyOn( codeFlowCallbackService, 'authenticatedCallbackWithCode' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); callbackService .handleCallbackAndFireEvents('anyUrl', { configId: 'configId1' }, [ diff --git a/projects/angular-auth-oidc-client/src/lib/callback/periodically-token-check.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/callback/periodically-token-check.service.spec.ts index 9e3e3d31..16c81aac 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/periodically-token-check.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/periodically-token-check.service.spec.ts @@ -161,7 +161,7 @@ describe('PeriodicallyTokenCheckService', () => { tick(1000); - intervalService.runTokenValidationRunning.unsubscribe(); + intervalService.runTokenValidationRunning?.unsubscribe(); intervalService.runTokenValidationRunning = null; expect(isCurrentFlowCodeFlowWithRefreshTokensSpy).toHaveBeenCalled(); expect(resetSilentRenewRunningSpy).toHaveBeenCalled(); @@ -282,7 +282,7 @@ describe('PeriodicallyTokenCheckService', () => { configs[0] ); tick(1000); - intervalService.runTokenValidationRunning.unsubscribe(); + intervalService.runTokenValidationRunning?.unsubscribe(); intervalService.runTokenValidationRunning = null; expect(resetAuthorizationDataSpy).toHaveBeenCalledTimes(1); @@ -321,7 +321,7 @@ describe('PeriodicallyTokenCheckService', () => { tick(1000); - intervalService.runTokenValidationRunning.unsubscribe(); + intervalService.runTokenValidationRunning?.unsubscribe(); intervalService.runTokenValidationRunning = null; expect(refreshSessionWithRefreshTokensSpy).toHaveBeenCalled(); })); @@ -329,7 +329,7 @@ describe('PeriodicallyTokenCheckService', () => { describe('shouldStartPeriodicallyCheckForConfig', () => { it('returns false when there is no IdToken', () => { - spyOn(authStateService, 'getIdToken').and.returnValue(null); + spyOn(authStateService, 'getIdToken').and.returnValue(''); spyOn(flowsDataService, 'isSilentRenewRunning').and.returnValue(false); spyOn(userService, 'getUserDataFromStore').and.returnValue( 'some-userdata' diff --git a/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known-data.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known-data.service.spec.ts index eb2c0be4..afa97cc3 100644 --- a/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known-data.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known-data.service.spec.ts @@ -51,9 +51,9 @@ describe('AuthWellKnownDataService', () => { describe('getWellKnownDocument', () => { it('should add suffix if it does not exist on current URL', waitForAsync(() => { - const dataServiceSpy = spyOn(dataService, 'get').and.callFake(() => { - return of(null); - }); + const dataServiceSpy = spyOn(dataService, 'get').and.returnValue( + of(null) + ); const urlWithoutSuffix = 'myUrl'; const urlWithSuffix = `${urlWithoutSuffix}/.well-known/openid-configuration`; @@ -67,9 +67,9 @@ describe('AuthWellKnownDataService', () => { })); it('should not add suffix if it does exist on current url', waitForAsync(() => { - const dataServiceSpy = spyOn(dataService, 'get').and.callFake(() => { - return of(null); - }); + const dataServiceSpy = spyOn(dataService, 'get').and.returnValue( + of(null) + ); const urlWithSuffix = `myUrl/.well-known/openid-configuration`; (service as any) @@ -82,9 +82,9 @@ describe('AuthWellKnownDataService', () => { })); it('should not add suffix if it does exist in the middle of current url', waitForAsync(() => { - const dataServiceSpy = spyOn(dataService, 'get').and.callFake(() => { - return of(null); - }); + const dataServiceSpy = spyOn(dataService, 'get').and.returnValue( + of(null) + ); const urlWithSuffix = `myUrl/.well-known/openid-configuration/and/some/more/stuff`; (service as any) @@ -107,7 +107,7 @@ describe('AuthWellKnownDataService', () => { (service as any) .getWellKnownDocument('anyurl', { configId: 'configId1' }) .subscribe({ - next: (res) => { + next: (res: any) => { expect(res).toBeTruthy(); expect(res).toEqual(DUMMY_WELL_KNOWN_DOCUMENT); }, @@ -126,7 +126,7 @@ describe('AuthWellKnownDataService', () => { (service as any) .getWellKnownDocument('anyurl', { configId: 'configId1' }) .subscribe({ - next: (res) => { + next: (res: any) => { expect(res).toBeTruthy(); expect(res).toEqual(DUMMY_WELL_KNOWN_DOCUMENT); }, @@ -144,7 +144,7 @@ describe('AuthWellKnownDataService', () => { ); (service as any).getWellKnownDocument('anyurl', 'configId').subscribe({ - error: (err) => { + error: (err: any) => { expect(err).toBeTruthy(); }, }); @@ -153,9 +153,7 @@ describe('AuthWellKnownDataService', () => { describe('getWellKnownEndPointsForConfig', () => { it('calling internal getWellKnownDocument and maps', waitForAsync(() => { - spyOn(dataService, 'get').and.returnValue( - of({ jwks_uri: 'jwks_uri' }) - ); + spyOn(dataService, 'get').and.returnValue(of({ jwks_uri: 'jwks_uri' })); const spy = spyOn( service as any, @@ -176,7 +174,10 @@ describe('AuthWellKnownDataService', () => { it('throws error and logs if no authwellknownUrl is given', waitForAsync(() => { const loggerSpy = spyOn(loggerService, 'logError'); - const config = { configId: 'configId1', authWellknownEndpointUrl: null }; + const config = { + configId: 'configId1', + authWellknownEndpointUrl: undefined, + }; service.getWellKnownEndPointsForConfig(config).subscribe({ error: (error) => { diff --git a/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known-data.service.ts b/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known-data.service.ts index 32ac585c..48115bdd 100644 --- a/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known-data.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known-data.service.ts @@ -58,6 +58,6 @@ export class AuthWellKnownDataService { url = `${wellKnownEndpoint}${WELL_KNOWN_SUFFIX}`; } - return this.http.get(url, config).pipe(retry(2)); + return this.http.get(url, config).pipe(retry(2)); } } diff --git a/projects/angular-auth-oidc-client/src/lib/logoff-revoke/logoff-revocation.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/logoff-revoke/logoff-revocation.service.spec.ts index 9315be72..0428da7c 100644 --- a/projects/angular-auth-oidc-client/src/lib/logoff-revoke/logoff-revocation.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/logoff-revoke/logoff-revocation.service.spec.ts @@ -477,7 +477,7 @@ describe('Logout and Revoke Service', () => { // Arrange spyOn(urlService, 'getEndSessionUrl').and.returnValue('someValue'); const spy = jasmine.createSpy(); - const urlHandler = (url): void => { + const urlHandler = (url: string): void => { spy(url); }; const redirectSpy = spyOn(redirectService, 'redirectTo'); @@ -749,7 +749,7 @@ describe('Logout and Revoke Service', () => { ); spyOn(service, 'revokeAccessToken').and.returnValue(of({ any: 'thing' })); const logoffSpy = spyOn(service, 'logoff').and.returnValue(of(null)); - const urlHandler = (_url): void => undefined; + const urlHandler = (_url: string): void => undefined; const config = { configId: 'configId1' }; // Act @@ -771,7 +771,7 @@ describe('Logout and Revoke Service', () => { .withArgs('authWellKnownEndPoints', config) .and.returnValue({ revocationEndpoint: 'revocationEndpoint' }); - spyOn(storagePersistenceService, 'getRefreshToken').and.returnValue(null); + spyOn(storagePersistenceService, 'getRefreshToken').and.returnValue(''); const revokeRefreshTokenSpy = spyOn(service, 'revokeRefreshToken'); const revokeAccessTokenSpy = spyOn( service, @@ -793,7 +793,7 @@ describe('Logout and Revoke Service', () => { spyOn(storagePersistenceService, 'read') .withArgs('authWellKnownEndPoints', config) .and.returnValue({ revocationEndpoint: 'revocationEndpoint' }); - spyOn(storagePersistenceService, 'getRefreshToken').and.returnValue(null); + spyOn(storagePersistenceService, 'getRefreshToken').and.returnValue(''); const loggerSpy = spyOn(loggerService, 'logError'); spyOn(service, 'revokeAccessToken').and.returnValue( diff --git a/projects/angular-auth-oidc-client/src/lib/oidc.security.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/oidc.security.service.spec.ts index 5ac85c19..1105b93b 100644 --- a/projects/angular-auth-oidc-client/src/lib/oidc.security.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/oidc.security.service.spec.ts @@ -10,6 +10,7 @@ import { AuthWellKnownService } from './config/auth-well-known/auth-well-known.s import { ConfigurationService } from './config/config.service'; import { FlowsDataService } from './flows/flows-data.service'; import { CheckSessionService } from './iframe/check-session.service'; +import { LoginResponse } from './login/login-response'; import { LoginService } from './login/login.service'; import { LogoffRevocationService } from './logoff-revoke/logoff-revocation.service'; import { OidcSecurityService } from './oidc.security.service'; @@ -165,7 +166,7 @@ describe('OidcSecurityService', () => { const spy = spyOn( authWellKnownService, 'queryAndStoreAuthWellKnownEndPoints' - ).and.returnValue(of(null)); + ).and.returnValue(of({})); oidcSecurityService.preloadAuthWellKnownDocument().subscribe(() => { expect(spy).toHaveBeenCalledOnceWith(config); @@ -248,7 +249,7 @@ describe('OidcSecurityService', () => { ); const spy = spyOn(checkAuthService, 'checkAuth').and.returnValue( - of(null) + of({} as LoginResponse) ); oidcSecurityService.checkAuth().subscribe(() => { @@ -264,7 +265,7 @@ describe('OidcSecurityService', () => { ); const spy = spyOn(checkAuthService, 'checkAuth').and.returnValue( - of(null) + of({} as LoginResponse) ); oidcSecurityService.checkAuth('some-url').subscribe(() => { @@ -282,7 +283,7 @@ describe('OidcSecurityService', () => { ); const spy = spyOn(checkAuthService, 'checkAuthMultiple').and.returnValue( - of(null) + of([{}] as LoginResponse[]) ); oidcSecurityService.checkAuthMultiple().subscribe(() => { @@ -298,7 +299,7 @@ describe('OidcSecurityService', () => { ); const spy = spyOn(checkAuthService, 'checkAuthMultiple').and.returnValue( - of(null) + of([{}] as LoginResponse[]) ); oidcSecurityService.checkAuthMultiple('some-url').subscribe(() => { @@ -336,7 +337,7 @@ describe('OidcSecurityService', () => { const spy = spyOn( checkAuthService, 'checkAuthIncludingServer' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as LoginResponse)); oidcSecurityService.checkAuthIncludingServer().subscribe(() => { expect(spy).toHaveBeenCalledOnceWith(config, [config]); @@ -562,7 +563,7 @@ describe('OidcSecurityService', () => { of({ allConfigs: [config], currentConfig: config }) ); const spy = spyOn(loginService, 'loginWithPopUp').and.callFake(() => - of(null) + of({} as LoginResponse) ); oidcSecurityService.authorizeWithPopUp().subscribe(() => { @@ -587,7 +588,7 @@ describe('OidcSecurityService', () => { const spy = spyOn( refreshSessionService, 'userForceRefreshSession' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as LoginResponse)); oidcSecurityService.forceRefreshSession().subscribe(() => { expect(spy).toHaveBeenCalledOnceWith(config, [config], undefined); diff --git a/projects/angular-auth-oidc-client/src/lib/oidc.security.service.ts b/projects/angular-auth-oidc-client/src/lib/oidc.security.service.ts index f4773fcf..28072903 100644 --- a/projects/angular-auth-oidc-client/src/lib/oidc.security.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/oidc.security.service.ts @@ -235,7 +235,7 @@ export class OidcSecurityService { * * @returns A object with the authentication result */ - getAuthenticationResult(configId?: string): Observable { + getAuthenticationResult(configId?: string): Observable { return this.configurationService .getOpenIDConfiguration(configId) .pipe( diff --git a/projects/angular-auth-oidc-client/src/lib/provide-auth.spec.ts b/projects/angular-auth-oidc-client/src/lib/provide-auth.spec.ts index ca38fa28..e5c74d3b 100644 --- a/projects/angular-auth-oidc-client/src/lib/provide-auth.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/provide-auth.spec.ts @@ -45,7 +45,7 @@ describe('provideAuth', () => { provideAuth({ loader: { provide: StsConfigLoader, - useFactory: () => new StsConfigHttpLoader(of(null)), + useFactory: () => new StsConfigHttpLoader(of({})), }, }), { diff --git a/projects/angular-auth-oidc-client/src/lib/storage/browser-storage.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/storage/browser-storage.service.spec.ts index a1ed516d..c4cfe98c 100644 --- a/projects/angular-auth-oidc-client/src/lib/storage/browser-storage.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/storage/browser-storage.service.spec.ts @@ -161,7 +161,7 @@ describe('Browser Service', () => { describe('hasStorage', () => { it('returns false if there is no storage', () => { - Storage = undefined; + (Storage as any) = undefined; expect((service as any).hasStorage()).toBeFalse(); Storage = Storage; }); diff --git a/projects/angular-auth-oidc-client/src/lib/storage/storage-persistence.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/storage/storage-persistence.service.spec.ts index 573213d5..9cf90aa8 100644 --- a/projects/angular-auth-oidc-client/src/lib/storage/storage-persistence.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/storage/storage-persistence.service.spec.ts @@ -93,7 +93,7 @@ describe('Storage Persistence Service', () => { it('should call oidcSecurityStorage.clear()', () => { const clearSpy = spyOn(securityStorage, 'clear'); - service.clear(null); + service.clear({}); expect(clearSpy).toHaveBeenCalledTimes(1); }); diff --git a/projects/angular-auth-oidc-client/src/lib/user-data/user-service.spec.ts b/projects/angular-auth-oidc-client/src/lib/user-data/user-service.spec.ts index 874a6118..830d350f 100644 --- a/projects/angular-auth-oidc-client/src/lib/user-data/user-service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/user-data/user-service.spec.ts @@ -535,7 +535,7 @@ describe('User Service', () => { .withArgs('authWellKnownEndPoints', config) .and.returnValue(null); serviceAsAny.getIdentityUserData(config).subscribe({ - error: (err) => { + error: (err: any) => { expect(err).toBeTruthy(); }, }); @@ -552,7 +552,7 @@ describe('User Service', () => { .withArgs('authWellKnownEndPoints', config) .and.returnValue({ userInfoEndpoint: null }); serviceAsAny.getIdentityUserData(config).subscribe({ - error: (err) => { + error: (err: any) => { expect(err).toBeTruthy(); }, }); @@ -596,7 +596,7 @@ describe('User Service', () => { ); (userService as any).getIdentityUserData(config).subscribe({ - next: (res) => { + next: (res: any) => { expect(res).toBeTruthy(); expect(res).toEqual(DUMMY_USER_DATA); }, @@ -621,7 +621,7 @@ describe('User Service', () => { ); (userService as any).getIdentityUserData(config).subscribe({ - next: (res) => { + next: (res: any) => { expect(res).toBeTruthy(); expect(res).toEqual(DUMMY_USER_DATA); }, @@ -647,7 +647,7 @@ describe('User Service', () => { ); (userService as any).getIdentityUserData(config).subscribe({ - error: (err) => { + error: (err: any) => { expect(err).toBeTruthy(); }, }); diff --git a/projects/angular-auth-oidc-client/src/lib/utils/equality/equality.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/utils/equality/equality.service.spec.ts index 54079e02..98f18f78 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/equality/equality.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/equality/equality.service.spec.ts @@ -154,21 +154,6 @@ describe('EqualityService Tests', () => { input2: 'value1', expected: true, }, - { - input1: null, - input2: 'value2', - expected: false, - }, - { - input1: 'value1', - input2: null, - expected: false, - }, - { - input1: null, - input2: null, - expected: false, - }, { input1: 'value1', input2: 'value2', @@ -177,42 +162,42 @@ describe('EqualityService Tests', () => { // old "x" (string) , [x] new invalid { input1: 'value1', - input2: ['value2'], + input2: ['value2'] as any[], expected: false, }, // old [x], new "x" (string) invalid { - input1: ['value2'], + input1: ['value2'] as any[], input2: 'value1', expected: false, }, { - input1: ['value1'], - input2: ['value2'], + input1: ['value1'] as any[], + input2: ['value2'] as any[], expected: false, }, // old [x,y,z], new [x,y] invalid // old [x], new [y,x] invalid { - input1: ['value1'], - input2: ['value1', 'value2'], + input1: ['value1'] as any[], + input2: ['value1', 'value2'] as any[], expected: false, }, { - input1: ['value1', 'value2'], - input2: ['value1', 'value2'], + input1: ['value1', 'value2'] as any[], + input2: ['value1', 'value2'] as any[], expected: true, }, // old [x,y], new [y,x] valid { - input1: ['value1', 'value2'], - input2: ['value2', 'value1'], + input1: ['value1', 'value2'] as any[], + input2: ['value2', 'value1'] as any[], expected: true, }, // old [x,y,z], new [y,z,x] valid { - input1: ['x', 'y', 'z'], - input2: ['y', 'z', 'x'], + input1: ['x', 'y', 'z'] as any[], + input2: ['y', 'z', 'x'] as any[], expected: true, }, ]; diff --git a/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.spec.ts index 35978db6..7e2755c7 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.spec.ts @@ -57,7 +57,7 @@ describe('CurrentUrlService with existing Url', () => { }); it('returns the state param for the URL if one is passed as null', () => { - const stateParam = service.getStateParamFromCurrentUrl(null); + const stateParam = service.getStateParamFromCurrentUrl(undefined); expect(stateParam).toBe('my-state'); }); diff --git a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.spec.ts index 866c4343..1d3b951b 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.spec.ts @@ -899,17 +899,17 @@ describe('UrlService Tests', () => { it('getRevocationEndpointUrl returns null when there is not revociationendpoint given', () => { spyOn(storagePersistenceService, 'read') - .withArgs('authWellKnownEndPoints', null) + .withArgs('authWellKnownEndPoints', {}) .and.returnValue({ revocationEndpoint: null, }); - const value = service.getRevocationEndpointUrl(null); + const value = service.getRevocationEndpointUrl({}); expect(value).toBeNull(); }); it('getRevocationEndpointUrl returns null when there is no wellKnownEndpoints given', () => { - const value = service.getRevocationEndpointUrl(null); + const value = service.getRevocationEndpointUrl({}); expect(value).toBeNull(); }); From f161de83a51c9de4e160aa0b73ef078aab4a3b99 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Thu, 4 Jan 2024 07:56:44 +0100 Subject: [PATCH 16/56] Add LoginResponse import and update checkAuth return value --- .../login/popup/popup-login.service.spec.ts | 21 ++++++++++++------- .../src/lib/login/popup/popup.service.spec.ts | 8 +++---- .../standard/standard-login.service.spec.ts | 2 +- 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/login/popup/popup-login.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/popup/popup-login.service.spec.ts index 2a19d406..e63e0f27 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/popup/popup-login.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/popup/popup-login.service.spec.ts @@ -6,6 +6,7 @@ import { CheckAuthService } from '../../auth-state/check-auth.service'; import { AuthWellKnownService } from '../../config/auth-well-known/auth-well-known.service'; import { LoggerService } from '../../logging/logger.service'; import { UrlService } from '../../utils/url/url.service'; +import { LoginResponse } from '../login-response'; import { ResponseTypeValidationService } from '../response-type-validation/response-type-validation.service'; import { PopUpLoginService } from './popup-login.service'; import { PopupResult } from './popup-result'; @@ -93,7 +94,9 @@ describe('PopUpLoginService', () => { of({} as PopupResult) ); spyOn(urlService, 'getAuthorizeUrl').and.returnValue(of('someUrl')); - spyOn(checkAuthService, 'checkAuth').and.returnValue(of(null)); + spyOn(checkAuthService, 'checkAuth').and.returnValue( + of({} as LoginResponse) + ); popUpLoginService .loginWithPopUpStandard(config, [config]) @@ -120,7 +123,9 @@ describe('PopUpLoginService', () => { spyOnProperty(popupService, 'result$').and.returnValue( of({} as PopupResult) ); - spyOn(checkAuthService, 'checkAuth').and.returnValue(of(null)); + spyOn(checkAuthService, 'checkAuth').and.returnValue( + of({} as LoginResponse) + ); const popupSpy = spyOn(popupService, 'openPopUp'); popUpLoginService @@ -150,7 +155,7 @@ describe('PopUpLoginService', () => { of({ isAuthenticated: true, configId: 'configId1', - idToken: null, + idToken: '', userData: { any: 'userData' }, accessToken: 'anyAccessToken', }) @@ -174,7 +179,7 @@ describe('PopUpLoginService', () => { expect(result).toEqual({ isAuthenticated: true, configId: 'configId1', - idToken: null, + idToken: '', userData: { any: 'userData' }, accessToken: 'anyAccessToken', }); @@ -199,9 +204,9 @@ describe('PopUpLoginService', () => { spyOn(urlService, 'getAuthorizeUrl').and.returnValue(of('someUrl')); spyOn(popupService, 'openPopUp'); const checkAuthSpy = spyOn(checkAuthService, 'checkAuth').and.returnValue( - of(null) + of({} as LoginResponse) ); - const popupResult: PopupResult = { userClosed: true }; + const popupResult = { userClosed: true } as PopupResult; spyOnProperty(popupService, 'result$').and.returnValue(of(popupResult)); @@ -213,9 +218,9 @@ describe('PopUpLoginService', () => { isAuthenticated: false, errorMessage: 'User closed popup', configId: 'configId1', - idToken: null, + idToken: '', userData: null, - accessToken: null, + accessToken: '', }); }); })); diff --git a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts index 6169df9b..31ebb848 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts @@ -261,7 +261,7 @@ describe('PopUpService', () => { tick(200); - expect(popupResult).toEqual({ userClosed: true }); + expect(popupResult).toEqual({ userClosed: true } as PopupResult); expect(cleanUpSpy).toHaveBeenCalled(); })); }); @@ -275,7 +275,7 @@ describe('PopUpService', () => { const sendMessageSpy = spyOn(popUpService as any, 'sendMessage'); // act - popUpService.sendMessageToMainWindow(''); + popUpService.sendMessageToMainWindow('', {}); // assert expect(sendMessageSpy).not.toHaveBeenCalled(); @@ -289,7 +289,7 @@ describe('PopUpService', () => { const sendMessageSpy = spyOn(window.opener, 'postMessage'); // act - popUpService.sendMessageToMainWindow('someUrl'); + popUpService.sendMessageToMainWindow('someUrl', {}); // assert expect(sendMessageSpy).toHaveBeenCalledOnceWith( @@ -305,7 +305,7 @@ describe('PopUpService', () => { const spy = spyOn(window, 'removeEventListener').and.callFake( () => undefined ); - const listener = null; + const listener: any = null; // act (popUpService as any).cleanUp(listener, { configId: 'configId1' }); diff --git a/projects/angular-auth-oidc-client/src/lib/login/standard/standard-login.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/standard/standard-login.service.spec.ts index 8ae593aa..4f0de92a 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/standard/standard-login.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/standard/standard-login.service.spec.ts @@ -160,7 +160,7 @@ describe('StandardLoginService', () => { () => undefined ); const spy = jasmine.createSpy(); - const urlHandler = (url): void => { + const urlHandler = (url: any): void => { spy(url); }; From ba4aa11af4c5d39afaf0ee67d37a0797a2fe519d Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Thu, 4 Jan 2024 08:55:10 +0100 Subject: [PATCH 17/56] Fix null reference errors and update dependencies --- .../user-callback-handler.service.spec.ts | 67 ++++++++++--------- .../lib/iframe/silent-renew.service.spec.ts | 16 ++--- .../src/lib/logging/logger.service.spec.ts | 8 +-- .../lib/login/par/par-login.service.spec.ts | 17 +++-- .../src/lib/login/par/par.service.spec.ts | 4 +- 5 files changed, 58 insertions(+), 54 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/user-callback-handler.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/user-callback-handler.service.spec.ts index 8e02a488..8e452426 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/user-callback-handler.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/user-callback-handler.service.spec.ts @@ -6,6 +6,7 @@ import { LoggerService } from '../../logging/logger.service'; import { UserService } from '../../user-data/user.service'; import { StateValidationResult } from '../../validation/state-validation-result'; import { ValidationResult } from '../../validation/validation-result'; +import { CallbackContext } from '../callback-context'; import { FlowsDataService } from '../flows-data.service'; import { ResetAuthDataService } from '../reset-auth-data.service'; import { UserCallbackHandlerService } from './user-callback-handler.service'; @@ -54,16 +55,16 @@ describe('UserCallbackHandlerService', () => { 'decoded' ); const callbackContext = { - code: null, - refreshToken: null, - state: null, + code: '', + refreshToken: '', + state: '', sessionState: null, authResult: { session_state: 'mystate' }, isRenewProcess: false, jwtKeys: null, validationResult: svr, - existingIdToken: null, - }; + existingIdToken: '', + } as CallbackContext; const allConfigs = [ { @@ -90,16 +91,16 @@ describe('UserCallbackHandlerService', () => { 'decoded' ); const callbackContext = { - code: null, - refreshToken: null, - state: null, + code: '', + refreshToken: '', + state: '', sessionState: null, authResult: { session_state: 'mystate' }, isRenewProcess: true, jwtKeys: null, validationResult: svr, existingIdToken: null, - }; + } as CallbackContext; const allConfigs = [ { configId: 'configId1', @@ -124,16 +125,16 @@ describe('UserCallbackHandlerService', () => { 'decoded' ); const callbackContext = { - code: null, + code: '', refreshToken: 'somerefreshtoken', - state: null, + state: '', sessionState: null, authResult: { session_state: 'mystate' }, isRenewProcess: false, jwtKeys: null, validationResult: svr, existingIdToken: null, - }; + } as CallbackContext; const allConfigs = [ { configId: 'configId1', @@ -153,16 +154,16 @@ describe('UserCallbackHandlerService', () => { it('does NOT call flowsDataService.setSessionState if autoUserInfo is false isRenewProcess is false, refreshToken has value, id_token is false', waitForAsync(() => { const svr = new StateValidationResult('accesstoken', '', true, ''); const callbackContext = { - code: null, + code: '', refreshToken: 'somerefreshtoken', - state: null, + state: '', sessionState: null, authResult: { session_state: 'mystate' }, isRenewProcess: false, jwtKeys: null, validationResult: svr, existingIdToken: null, - }; + } as CallbackContext; const allConfigs = [ { configId: 'configId1', @@ -188,16 +189,16 @@ describe('UserCallbackHandlerService', () => { 'decoded' ); const callbackContext = { - code: null, + code: '', refreshToken: 'somerefreshtoken', - state: null, + state: '', sessionState: null, authResult: { session_state: 'mystate' }, isRenewProcess: false, jwtKeys: null, validationResult: svr, existingIdToken: null, - }; + } as CallbackContext; const allConfigs = [ { @@ -231,16 +232,16 @@ describe('UserCallbackHandlerService', () => { 'decoded' ); const callbackContext = { - code: null, + code: '', refreshToken: 'somerefreshtoken', - state: null, + state: '', sessionState: null, authResult: { session_state: 'mystate' }, isRenewProcess: false, jwtKeys: null, validationResult: svr, existingIdToken: null, - }; + } as CallbackContext; const allConfigs = [ { @@ -277,16 +278,16 @@ describe('UserCallbackHandlerService', () => { ValidationResult.MaxOffsetExpired ); const callbackContext = { - code: null, + code: '', refreshToken: 'somerefreshtoken', - state: null, + state: '', sessionState: null, authResult: { session_state: 'mystate' }, isRenewProcess: false, jwtKeys: null, validationResult: svr, existingIdToken: null, - }; + } as CallbackContext; const allConfigs = [ { @@ -324,16 +325,16 @@ describe('UserCallbackHandlerService', () => { ValidationResult.MaxOffsetExpired ); const callbackContext = { - code: null, + code: '', refreshToken: '', // something falsy - state: null, + state: '', sessionState: null, authResult: { session_state: 'mystate' }, isRenewProcess: false, jwtKeys: null, validationResult: svr, existingIdToken: null, - }; + } as CallbackContext; const allConfigs = [ { @@ -367,16 +368,16 @@ describe('UserCallbackHandlerService', () => { ValidationResult.MaxOffsetExpired ); const callbackContext = { - code: null, + code: '', refreshToken: 'somerefreshtoken', - state: null, + state: '', sessionState: null, authResult: { session_state: 'mystate' }, isRenewProcess: false, jwtKeys: null, validationResult: svr, existingIdToken: null, - }; + } as CallbackContext; const allConfigs = [ { @@ -418,16 +419,16 @@ describe('UserCallbackHandlerService', () => { ValidationResult.MaxOffsetExpired ); const callbackContext = { - code: null, + code: '', refreshToken: 'somerefreshtoken', - state: null, + state: '', sessionState: null, authResult: { session_state: 'mystate' }, isRenewProcess: false, jwtKeys: null, validationResult: svr, existingIdToken: null, - }; + } as CallbackContext; const allConfigs = [ { diff --git a/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.spec.ts index 7ebfd10c..9987db37 100644 --- a/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.spec.ts @@ -139,10 +139,10 @@ describe('SilentRenewService ', () => { const spy = spyOn( flowsService, 'processSilentRenewCodeFlowCallback' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const expectedContext = { code: 'some-code', - refreshToken: null, + refreshToken: '', state: 'some-state', sessionState: 'some-session-state', authResult: null, @@ -150,7 +150,7 @@ describe('SilentRenewService ', () => { jwtKeys: null, validationResult: null, existingIdToken: null, - }; + } as CallbackContext; const url = 'url-part-1'; const urlParts = 'code=some-code&state=some-state&session_state=some-session-state'; @@ -173,7 +173,7 @@ describe('SilentRenewService ', () => { const spy = spyOn( flowsService, 'processSilentRenewCodeFlowCallback' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const authStateServiceSpy = spyOn( authStateService, 'updateAndPublishAuthState' @@ -223,7 +223,7 @@ describe('SilentRenewService ', () => { spyOn( implicitFlowCallbackService, 'authenticatedImplicitFlowCallback' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const eventData = { detail: null } as CustomEvent; const allConfigs = [{ configId: 'configId1' }]; @@ -244,7 +244,7 @@ describe('SilentRenewService ', () => { const authorizedImplicitFlowCallbackSpy = spyOn( implicitFlowCallbackService, 'authenticatedImplicitFlowCallback' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const eventData = { detail: 'detail' } as CustomEvent; const allConfigs = [{ configId: 'configId1' }]; @@ -267,7 +267,7 @@ describe('SilentRenewService ', () => { const codeFlowCallbackSilentRenewIframe = spyOn( silentRenewService, 'codeFlowCallbackSilentRenewIframe' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const eventData = { detail: 'detail?detail2' } as CustomEvent; const allConfigs = [{ configId: 'configId1' }]; @@ -289,7 +289,7 @@ describe('SilentRenewService ', () => { const codeFlowCallbackSilentRenewIframe = spyOn( silentRenewService, 'codeFlowCallbackSilentRenewIframe' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const eventData = { detail: 'detail?detail2' } as CustomEvent; const allConfigs = [{ configId: 'configId1' }]; diff --git a/projects/angular-auth-oidc-client/src/lib/logging/logger.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/logging/logger.service.spec.ts index 17acdb2b..7da12b92 100644 --- a/projects/angular-auth-oidc-client/src/lib/logging/logger.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/logging/logger.service.spec.ts @@ -1,8 +1,8 @@ import { TestBed } from '@angular/core/testing'; -import { LoggerService } from './logger.service'; import { AbstractLoggerService } from './abstract-logger.service'; import { ConsoleLoggerService } from './console-logger.service'; import { LogLevel } from './log-level'; +import { LoggerService } from './logger.service'; describe('Logger Service', () => { let loggerService: LoggerService; @@ -73,7 +73,7 @@ describe('Logger Service', () => { const spy = spyOn(console, 'warn'); loggerService.logWarning( - { configId: 'configId1', logLevel: null }, + { configId: 'configId1', logLevel: undefined }, 'some message' ); expect(spy).not.toHaveBeenCalled(); @@ -82,7 +82,7 @@ describe('Logger Service', () => { it('should not log if no config is given', () => { const spy = spyOn(console, 'warn'); - loggerService.logWarning(null, 'some message'); + loggerService.logWarning({}, 'some message'); expect(spy).not.toHaveBeenCalled(); }); @@ -168,7 +168,7 @@ describe('Logger Service', () => { const spy = spyOn(console, 'debug'); loggerService.logDebug( - { configId: 'configId1', logLevel: null }, + { configId: 'configId1', logLevel: undefined }, 'some message' ); expect(spy).not.toHaveBeenCalled(); diff --git a/projects/angular-auth-oidc-client/src/lib/login/par/par-login.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/par/par-login.service.spec.ts index 3f03950c..b96bc572 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/par/par-login.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/par/par-login.service.spec.ts @@ -6,6 +6,7 @@ import { AuthWellKnownService } from '../../config/auth-well-known/auth-well-kno import { LoggerService } from '../../logging/logger.service'; import { RedirectService } from '../../utils/redirect/redirect.service'; import { UrlService } from '../../utils/url/url.service'; +import { LoginResponse } from '../login-response'; import { PopupResult } from '../popup/popup-result'; import { PopUpService } from '../popup/popup.service'; import { ResponseTypeValidationService } from '../response-type-validation/response-type-validation.service'; @@ -225,7 +226,7 @@ describe('ParLoginService', () => { spyOn(urlService, 'getAuthorizeParUrl').and.returnValue('some-par-url'); const redirectToSpy = spyOn(redirectService, 'redirectTo'); const spy = jasmine.createSpy(); - const urlHandler = (url): void => { + const urlHandler = (url: any): void => { spy(url); }; @@ -376,7 +377,9 @@ describe('ParLoginService', () => { of({ requestUri: 'requestUri' } as ParResponse) ); spyOn(urlService, 'getAuthorizeParUrl').and.returnValue('some-par-url'); - spyOn(checkAuthService, 'checkAuth').and.returnValue(of(null)); + spyOn(checkAuthService, 'checkAuth').and.returnValue( + of({} as LoginResponse) + ); spyOnProperty(popupService, 'result$').and.returnValue( of({} as PopupResult) ); @@ -413,7 +416,7 @@ describe('ParLoginService', () => { of({ isAuthenticated: true, configId: 'configId1', - idToken: null, + idToken: '', userData: { any: 'userData' }, accessToken: 'anyAccessToken', }) @@ -435,7 +438,7 @@ describe('ParLoginService', () => { expect(result).toEqual({ isAuthenticated: true, configId: 'configId1', - idToken: null, + idToken: '', userData: { any: 'userData' }, accessToken: 'anyAccessToken', }); @@ -465,7 +468,7 @@ describe('ParLoginService', () => { spyOn(urlService, 'getAuthorizeParUrl').and.returnValue('some-par-url'); const checkAuthSpy = spyOn(checkAuthService, 'checkAuth'); - const popupResult: PopupResult = { userClosed: true }; + const popupResult = { userClosed: true } as PopupResult; spyOnProperty(popupService, 'result$').and.returnValue(of(popupResult)); @@ -475,9 +478,9 @@ describe('ParLoginService', () => { isAuthenticated: false, errorMessage: 'User closed popup', configId: 'configId1', - idToken: null, + idToken: '', userData: null, - accessToken: null, + accessToken: '', }); }); })); diff --git a/projects/angular-auth-oidc-client/src/lib/login/par/par.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/par/par.service.spec.ts index 40f56e11..98dd29fe 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/par/par.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/par/par.service.spec.ts @@ -55,7 +55,7 @@ describe('ParService', () => { describe('postParRequest', () => { it('throws error if authWellKnownEndPoints does not exist in storage', waitForAsync(() => { spyOn(urlService, 'createBodyForParCodeFlowRequest').and.returnValue( - null + of(null) ); spyOn(storagePersistenceService, 'read') .withArgs('authWellKnownEndPoints', { configId: 'configId1' }) @@ -71,7 +71,7 @@ describe('ParService', () => { it('throws error if par endpoint does not exist in storage', waitForAsync(() => { spyOn(urlService, 'createBodyForParCodeFlowRequest').and.returnValue( - null + of(null) ); spyOn(storagePersistenceService, 'read') .withArgs('authWellKnownEndPoints', { configId: 'configId1' }) From a657b7a37771338a2b7ec9bf9b3c7c1515d32635 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Thu, 4 Jan 2024 09:41:19 +0100 Subject: [PATCH 18/56] Fix type annotations and initialize variables --- .../implicit-flow-callback.service.spec.ts | 3 ++- .../code-flow-callback-handler.service.spec.ts | 10 +++++----- ...story-jwt-keys-callback-handler.service.spec.ts | 10 ++++++---- .../implicit-flow-callback-handler.service.spec.ts | 12 ++++++------ ...efresh-session-callback-handler.service.spec.ts | 7 ++++--- .../refresh-token-callback-handler.service.spec.ts | 2 +- .../src/lib/iframe/check-session.service.spec.ts | 8 ++++---- .../src/lib/login/popup/popup.service.spec.ts | 14 +++++++------- 8 files changed, 35 insertions(+), 31 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/callback/implicit-flow-callback.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/callback/implicit-flow-callback.service.spec.ts index 9e924284..233e38cd 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/implicit-flow-callback.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/implicit-flow-callback.service.spec.ts @@ -3,6 +3,7 @@ import { Router } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { of, throwError } from 'rxjs'; import { mockClass } from '../../test/auto-mock'; +import { CallbackContext } from '../flows/callback-context'; import { FlowsDataService } from '../flows/flows-data.service'; import { FlowsService } from '../flows/flows.service'; import { ImplicitFlowCallbackService } from './implicit-flow-callback.service'; @@ -44,7 +45,7 @@ describe('ImplicitFlowCallbackService ', () => { const spy = spyOn( flowsService, 'processImplicitFlowCallback' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const config = { configId: 'configId1', triggerAuthorizationResultEvent: true, diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/code-flow-callback-handler.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/code-flow-callback-handler.service.spec.ts index f27a94b6..f2ceddb6 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/code-flow-callback-handler.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/code-flow-callback-handler.service.spec.ts @@ -58,7 +58,7 @@ describe('CodeFlowCallbackHandlerService', () => { 'getUrlParameter' ).and.returnValue('params'); - getUrlParameterSpy.withArgs('any-url', 'state').and.returnValue(null); + getUrlParameterSpy.withArgs('any-url', 'state').and.returnValue(''); service.codeFlowCallback('any-url', { configId: 'configId1' }).subscribe({ error: (err) => { @@ -73,7 +73,7 @@ describe('CodeFlowCallbackHandlerService', () => { 'getUrlParameter' ).and.returnValue('params'); - getUrlParameterSpy.withArgs('any-url', 'code').and.returnValue(null); + getUrlParameterSpy.withArgs('any-url', 'code').and.returnValue(''); service.codeFlowCallback('any-url', { configId: 'configId1' }).subscribe({ error: (err) => { @@ -87,15 +87,15 @@ describe('CodeFlowCallbackHandlerService', () => { const expectedCallbackContext = { code: 'params', - refreshToken: null, + refreshToken: '', state: 'params', sessionState: 'params', authResult: null, isRenewProcess: false, jwtKeys: null, validationResult: null, - existingIdToken: null, - }; + existingIdToken: '', + } as CallbackContext; service .codeFlowCallback('any-url', { configId: 'configId1' }) diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/history-jwt-keys-callback-handler.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/history-jwt-keys-callback-handler.service.spec.ts index ed6e6c04..575aa1c3 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/history-jwt-keys-callback-handler.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/history-jwt-keys-callback-handler.service.spec.ts @@ -6,7 +6,7 @@ import { LoggerService } from '../../logging/logger.service'; import { StoragePersistenceService } from '../../storage/storage-persistence.service'; import { JwtKey, JwtKeys } from '../../validation/jwtkeys'; import { ValidationResult } from '../../validation/validation-result'; -import { CallbackContext, AuthResult } from '../callback-context'; +import { AuthResult, CallbackContext } from '../callback-context'; import { FlowsDataService } from '../flows-data.service'; import { ResetAuthDataService } from '../reset-auth-data.service'; import { SigninKeyDataService } from '../signin-key-data.service'; @@ -272,7 +272,9 @@ describe('HistoryJwtKeysCallbackHandlerService', () => { }, ]; - spyOn(signInKeyDataService, 'getSigningKeys').and.returnValue(of(null)); + spyOn(signInKeyDataService, 'getSigningKeys').and.returnValue( + of({} as JwtKeys) + ); service .callbackHistoryAndResetJwtKeys( callbackContext, @@ -381,7 +383,7 @@ describe('HistoryJwtKeysCallbackHandlerService', () => { expect(updateAndPublishAuthStateSpy).toHaveBeenCalledOnceWith({ isAuthenticated: false, validationResult: ValidationResult.SecureTokenServerError, - isRenewProcess: undefined, + isRenewProcess: false, }); }, }); @@ -421,7 +423,7 @@ describe('HistoryJwtKeysCallbackHandlerService', () => { expect(updateAndPublishAuthStateSpy).toHaveBeenCalledOnceWith({ isAuthenticated: false, validationResult: ValidationResult.LoginRequired, - isRenewProcess: undefined, + isRenewProcess: false, }); }, }); diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/implicit-flow-callback-handler.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/implicit-flow-callback-handler.service.spec.ts index 77fba238..4e58e949 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/implicit-flow-callback-handler.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/implicit-flow-callback-handler.service.spec.ts @@ -91,9 +91,9 @@ describe('ImplicitFlowCallbackHandlerService', () => { it('returns callbackContext if all params are good', waitForAsync(() => { spyOn(flowsDataService, 'isSilentRenewRunning').and.returnValue(true); const expectedCallbackContext = { - code: null, - refreshToken: null, - state: null, + code: '', + refreshToken: '', + state: '', sessionState: null, authResult: { anyHash: '' }, isRenewProcess: true, @@ -118,9 +118,9 @@ describe('ImplicitFlowCallbackHandlerService', () => { it('uses window location hash if no hash is passed', waitForAsync(() => { spyOn(flowsDataService, 'isSilentRenewRunning').and.returnValue(true); const expectedCallbackContext = { - code: null, - refreshToken: null, - state: null, + code: '', + refreshToken: '', + state: '', sessionState: null, authResult: { anyFakeHash: '' }, isRenewProcess: true, diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-session-callback-handler.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-session-callback-handler.service.spec.ts index ee17f6c8..5f01cb51 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-session-callback-handler.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-session-callback-handler.service.spec.ts @@ -2,6 +2,7 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { mockClass } from '../../../test/auto-mock'; import { AuthStateService } from '../../auth-state/auth-state.service'; import { LoggerService } from '../../logging/logger.service'; +import { CallbackContext } from '../callback-context'; import { FlowsDataService } from '../flows-data.service'; import { RefreshSessionCallbackHandlerService } from './refresh-session-callback-handler.service'; @@ -43,7 +44,7 @@ describe('RefreshSessionCallbackHandlerService', () => { spyOn(authStateService, 'getIdToken').and.returnValue('henlo-legger'); const expectedCallbackContext = { - code: null, + code: '', refreshToken: 'henlo-furiend', state: 'state-data', sessionState: null, @@ -52,7 +53,7 @@ describe('RefreshSessionCallbackHandlerService', () => { jwtKeys: null, validationResult: null, existingIdToken: 'henlo-legger', - }; + } as CallbackContext; service .refreshSessionWithRefreshTokens({ configId: 'configId1' }) @@ -66,7 +67,7 @@ describe('RefreshSessionCallbackHandlerService', () => { flowsDataService, 'getExistingOrCreateAuthStateControl' ).and.returnValue('state-data'); - spyOn(authStateService, 'getRefreshToken').and.returnValue(null); + spyOn(authStateService, 'getRefreshToken').and.returnValue(''); spyOn(authStateService, 'getIdToken').and.returnValue('henlo-legger'); service diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-token-callback-handler.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-token-callback-handler.service.spec.ts index 846ce5e6..d0acc21c 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-token-callback-handler.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-token-callback-handler.service.spec.ts @@ -53,7 +53,7 @@ describe('RefreshTokenCallbackHandlerService', () => { (service as any) .refreshTokensRequestTokens({} as CallbackContext) .subscribe({ - error: (err) => { + error: (err: any) => { expect(err).toBeTruthy(); }, }); diff --git a/projects/angular-auth-oidc-client/src/lib/iframe/check-session.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/iframe/check-session.service.spec.ts index 462d2539..884f48dc 100644 --- a/projects/angular-auth-oidc-client/src/lib/iframe/check-session.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/iframe/check-session.service.spec.ts @@ -6,9 +6,9 @@ import { LoggerService } from '../logging/logger.service'; import { OidcSecurityService } from '../oidc.security.service'; import { PublicEventsService } from '../public-events/public-events.service'; import { AbstractSecurityStorage } from '../storage/abstract-security-storage'; +import { DefaultSessionStorageService } from '../storage/default-sessionstorage.service'; import { StoragePersistenceService } from '../storage/storage-persistence.service'; import { PlatformProvider } from '../utils/platform-provider/platform.provider'; -import { DefaultSessionStorageService } from '../storage/default-sessionstorage.service'; import { CheckSessionService } from './check-session.service'; import { IFrameService } from './existing-iframe.service'; @@ -52,7 +52,7 @@ describe('CheckSessionService', () => { ); if (iFrameIdwhichshouldneverexist) { - iFrameIdwhichshouldneverexist.parentNode.removeChild( + iFrameIdwhichshouldneverexist.parentNode?.removeChild( iFrameIdwhichshouldneverexist ); } @@ -61,7 +61,7 @@ describe('CheckSessionService', () => { ); if (myiFrameForCheckSession) { - myiFrameForCheckSession.parentNode.removeChild(myiFrameForCheckSession); + myiFrameForCheckSession.parentNode?.removeChild(myiFrameForCheckSession); } }); @@ -301,7 +301,7 @@ describe('CheckSessionService', () => { serviceAsAny.lastIFrameRefresh = lastRefresh; serviceAsAny.iframeRefreshInterval = lastRefresh; - serviceAsAny.init().subscribe((result) => { + serviceAsAny.init().subscribe((result: any) => { expect(result).toBeUndefined(); }); })); diff --git a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts index 31ebb848..79eacd36 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts @@ -30,7 +30,7 @@ describe('PopUpService', () => { popUpService = TestBed.inject(PopUpService); }); - let store = {}; + let store: any = {}; const mockStorage = { getItem: (key: string): string => { return key in store ? store[key] : null; @@ -45,7 +45,7 @@ describe('PopUpService', () => { store = {}; }, length: 1, - key: (_i): string => '', + key: (_i: any): string => '', }; it('should create', () => { @@ -199,16 +199,16 @@ describe('PopUpService', () => { cleanUpSpy = spyOn(popUpService as any, 'cleanUp').and.callThrough(); - popupResult = undefined; + popupResult = {} as PopupResult; popUpService.result$.subscribe((result) => (popupResult = result)); }); it('message received with data', fakeAsync(() => { - let listener: (event: MessageEvent) => void; + let listener: (event: MessageEvent) => void = () => {}; spyOn(window, 'addEventListener').and.callFake( - (_, func) => (listener = func) + (_: any, func: any) => (listener = func) ); popUpService.openPopUp('url', {}, { configId: 'configId1' }); @@ -230,10 +230,10 @@ describe('PopUpService', () => { })); it('message received without data does return but cleanup does not throw event', fakeAsync(() => { - let listener: (event: MessageEvent) => void; + let listener: (event: MessageEvent) => void = () => {}; spyOn(window, 'addEventListener').and.callFake( - (_, func) => (listener = func) + (_: any, func: any) => (listener = func) ); const nextSpy = spyOn((popUpService as any).resultInternal$, 'next'); From f9b08d5719dd8add03277e202e25efd8e3d992d6 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Thu, 4 Jan 2024 09:56:12 +0100 Subject: [PATCH 19/56] Update configuration and callback context objects --- .../lib/auth-state/auth-state.service.spec.ts | 23 +++---- .../src/lib/auth.module.spec.ts | 4 +- .../auto-login-all-routes.guard.spec.ts | 62 +++++++++++++------ .../code-flow-callback.service.spec.ts | 3 +- ...resh-session-refresh-token.service.spec.ts | 3 +- .../callback/refresh-session.service.spec.ts | 12 ++-- .../src/lib/config/config.service.spec.ts | 13 ++-- .../config-validation.service.spec.ts | 16 +++-- 8 files changed, 84 insertions(+), 52 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.spec.ts index 135031d4..c8ff7b4e 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.spec.ts @@ -7,6 +7,7 @@ import { PublicEventsService } from '../public-events/public-events.service'; import { StoragePersistenceService } from '../storage/storage-persistence.service'; import { PlatformProvider } from '../utils/platform-provider/platform.provider'; import { TokenValidationService } from '../validation/token-validation.service'; +import { ValidationResult } from '../validation/validation-result'; import { AuthStateService } from './auth-state.service'; describe('Auth State Service', () => { @@ -95,13 +96,13 @@ describe('Auth State Service', () => { .withArgs(allConfigs[0]) .and.returnValue('someAccessToken') .withArgs(allConfigs[1]) - .and.returnValue(null); + .and.returnValue(''); spyOn(storagePersistenceService, 'getIdToken') .withArgs(allConfigs[0]) .and.returnValue('someIdToken') .withArgs(allConfigs[1]) - .and.returnValue(null); + .and.returnValue(''); const spy = spyOn( (authStateService as any).authenticatedInternal$, @@ -175,13 +176,13 @@ describe('Auth State Service', () => { .withArgs({ configId: 'configId1' }) .and.returnValue('someAccessToken') .withArgs({ configId: 'configId2' }) - .and.returnValue(null); + .and.returnValue(''); spyOn(storagePersistenceService, 'getIdToken') .withArgs({ configId: 'configId1' }) .and.returnValue('someIdToken') .withArgs({ configId: 'configId2' }) - .and.returnValue(null); + .and.returnValue(''); const spy = spyOn( (authStateService as any).authenticatedInternal$, @@ -210,7 +211,7 @@ describe('Auth State Service', () => { authStateService.updateAndPublishAuthState({ isAuthenticated: false, isRenewProcess: false, - validationResult: null, + validationResult: {} as ValidationResult, }); expect(eventsService.fireEvent).toHaveBeenCalledOnceWith( @@ -297,7 +298,7 @@ describe('Auth State Service', () => { spyOn(storagePersistenceService, 'getIdToken').and.returnValue(''); const result = authStateService.getAccessToken({ configId: 'configId1' }); - expect(result).toBe(null); + expect(result).toBe(''); }); it('returns false if storagePersistenceService returns something falsy but authorized', () => { @@ -328,7 +329,7 @@ describe('Auth State Service', () => { spyOn(storagePersistenceService, 'getAuthenticationResult') .withArgs({ configId: 'configId1' }) - .and.returnValue(null); + .and.returnValue({}); const result = authStateService.getAuthenticationResult({ configId: 'configId1', @@ -341,7 +342,7 @@ describe('Auth State Service', () => { spyOn(authStateService, 'isAuthenticated').and.returnValue(true); spyOn(storagePersistenceService, 'getAuthenticationResult') .withArgs({ configId: 'configId1' }) - .and.returnValue(null); + .and.returnValue({}); const result = authStateService.getAuthenticationResult({ configId: 'configId1', @@ -365,7 +366,7 @@ describe('Auth State Service', () => { configId: 'configId1', }); - expect(result.scope).toBe('HenloFuriend'); + expect(result?.scope).toBe('HenloFuriend'); }); }); @@ -375,7 +376,7 @@ describe('Auth State Service', () => { spyOn(storagePersistenceService, 'getIdToken').and.returnValue(''); const result = authStateService.getIdToken({ configId: 'configId1' }); - expect(result).toBe(null); + expect(result).toBe(''); }); it('isAuthorized is true returns decodeURIComponent(token)', () => { @@ -399,7 +400,7 @@ describe('Auth State Service', () => { configId: 'configId1', }); - expect(result).toBe(null); + expect(result).toBe(''); }); it('isAuthorized is true returns decodeURIComponent(token)', () => { diff --git a/projects/angular-auth-oidc-client/src/lib/auth.module.spec.ts b/projects/angular-auth-oidc-client/src/lib/auth.module.spec.ts index b49a148a..b471ef8c 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth.module.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth.module.spec.ts @@ -28,7 +28,7 @@ describe('AuthModule', () => { it('should create', () => { expect(AuthModule).toBeDefined(); - expect(AuthModule.forRoot(null)).toBeDefined(); + expect(AuthModule.forRoot({})).toBeDefined(); }); it('should provide config', () => { @@ -50,7 +50,7 @@ describe('AuthModule', () => { AuthModule.forRoot({ loader: { provide: StsConfigLoader, - useFactory: () => new StsConfigHttpLoader(of(null)), + useFactory: () => new StsConfigHttpLoader(of({})), }, }), ], diff --git a/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-all-routes.guard.spec.ts b/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-all-routes.guard.spec.ts index 5eff3a73..185546a4 100644 --- a/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-all-routes.guard.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-all-routes.guard.spec.ts @@ -1,5 +1,9 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; -import { Router, RouterStateSnapshot } from '@angular/router'; +import { + ActivatedRouteSnapshot, + Router, + RouterStateSnapshot, +} from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { Observable, of } from 'rxjs'; import { mockClass } from '../../test/auto-mock'; @@ -62,7 +66,7 @@ describe(`AutoLoginAllRoutesGuard`, () => { }); afterEach(() => { - storagePersistenceService.clear(null); + storagePersistenceService.clear({}); }); it('should create', () => { @@ -84,9 +88,12 @@ describe(`AutoLoginAllRoutesGuard`, () => { ); const loginSpy = spyOn(loginService, 'login'); - const canActivate$ = guard.canActivate(null, { - url: 'some-url1', - } as RouterStateSnapshot) as Observable; + const canActivate$ = guard.canActivate( + {} as ActivatedRouteSnapshot, + { + url: 'some-url1', + } as RouterStateSnapshot + ) as Observable; canActivate$.subscribe(() => { expect(saveRedirectRouteSpy).toHaveBeenCalledOnceWith( @@ -111,9 +118,12 @@ describe(`AutoLoginAllRoutesGuard`, () => { 'saveRedirectRoute' ); const loginSpy = spyOn(loginService, 'login'); - const canActivate$ = guard.canActivate(null, { - url: 'some-url1', - } as RouterStateSnapshot) as Observable; + const canActivate$ = guard.canActivate( + {} as ActivatedRouteSnapshot, + { + url: 'some-url1', + } as RouterStateSnapshot + ) as Observable; canActivate$.subscribe(() => { expect(saveRedirectRouteSpy).not.toHaveBeenCalled(); @@ -139,9 +149,12 @@ describe(`AutoLoginAllRoutesGuard`, () => { 'saveRedirectRoute' ); const loginSpy = spyOn(loginService, 'login'); - const canActivate$ = guard.canActivate(null, { - url: 'some-url1', - } as RouterStateSnapshot) as Observable; + const canActivate$ = guard.canActivate( + {} as ActivatedRouteSnapshot, + { + url: 'some-url1', + } as RouterStateSnapshot + ) as Observable; canActivate$.subscribe(() => { expect(saveRedirectRouteSpy).not.toHaveBeenCalled(); @@ -167,9 +180,12 @@ describe(`AutoLoginAllRoutesGuard`, () => { 'saveRedirectRoute' ); const loginSpy = spyOn(loginService, 'login'); - const canActivateChild$ = guard.canActivateChild(null, { - url: 'some-url1', - } as RouterStateSnapshot) as Observable; + const canActivateChild$ = guard.canActivateChild( + {} as ActivatedRouteSnapshot, + { + url: 'some-url1', + } as RouterStateSnapshot + ) as Observable; canActivateChild$.subscribe(() => { expect(saveRedirectRouteSpy).toHaveBeenCalledOnceWith( @@ -194,9 +210,12 @@ describe(`AutoLoginAllRoutesGuard`, () => { 'saveRedirectRoute' ); const loginSpy = spyOn(loginService, 'login'); - const canActivateChild$ = guard.canActivateChild(null, { - url: 'some-url1', - } as RouterStateSnapshot) as Observable; + const canActivateChild$ = guard.canActivateChild( + {} as ActivatedRouteSnapshot, + { + url: 'some-url1', + } as RouterStateSnapshot + ) as Observable; canActivateChild$.subscribe(() => { expect(saveRedirectRouteSpy).not.toHaveBeenCalled(); @@ -222,9 +241,12 @@ describe(`AutoLoginAllRoutesGuard`, () => { 'saveRedirectRoute' ); const loginSpy = spyOn(loginService, 'login'); - const canActivateChild$ = guard.canActivateChild(null, { - url: 'some-url1', - } as RouterStateSnapshot) as Observable; + const canActivateChild$ = guard.canActivateChild( + {} as ActivatedRouteSnapshot, + { + url: 'some-url1', + } as RouterStateSnapshot + ) as Observable; canActivateChild$.subscribe(() => { expect(saveRedirectRouteSpy).not.toHaveBeenCalled(); diff --git a/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.spec.ts index a7acdfc5..e2171941 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.spec.ts @@ -3,6 +3,7 @@ import { Router } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { of, throwError } from 'rxjs'; import { mockClass } from '../../test/auto-mock'; +import { CallbackContext } from '../flows/callback-context'; import { FlowsDataService } from '../flows/flows-data.service'; import { FlowsService } from '../flows/flows.service'; import { CodeFlowCallbackService } from './code-flow-callback.service'; @@ -44,7 +45,7 @@ describe('CodeFlowCallbackService ', () => { const spy = spyOn( flowsService, 'processCodeFlowCallback' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); //spyOn(configurationProvider, 'getOpenIDConfiguration').and.returnValue({ triggerAuthorizationResultEvent: true }); const config = { diff --git a/projects/angular-auth-oidc-client/src/lib/callback/refresh-session-refresh-token.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/callback/refresh-session-refresh-token.service.spec.ts index 2eb20282..4db3c62b 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/refresh-session-refresh-token.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/refresh-session-refresh-token.service.spec.ts @@ -1,6 +1,7 @@ import { fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { of, throwError } from 'rxjs'; import { mockClass } from '../../test/auto-mock'; +import { CallbackContext } from '../flows/callback-context'; import { FlowsService } from '../flows/flows.service'; import { ResetAuthDataService } from '../flows/reset-auth-data.service'; import { LoggerService } from '../logging/logger.service'; @@ -45,7 +46,7 @@ describe('RefreshSessionRefreshTokenService', () => { describe('refreshSessionWithRefreshTokens', () => { it('calls flowsService.processRefreshToken()', waitForAsync(() => { const spy = spyOn(flowsService, 'processRefreshToken').and.returnValue( - of(null) + of({} as CallbackContext) ); refreshSessionRefreshTokenService diff --git a/projects/angular-auth-oidc-client/src/lib/callback/refresh-session.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/callback/refresh-session.service.spec.ts index 6188ba4c..cf209f1b 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/refresh-session.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/refresh-session.service.spec.ts @@ -502,7 +502,7 @@ describe('RefreshSessionService ', () => { (refreshSessionService as any) .startRefreshSession() - .subscribe((result) => { + .subscribe((result: any) => { expect(result).toBe(null); }); })); @@ -512,7 +512,7 @@ describe('RefreshSessionService ', () => { (refreshSessionService as any) .startRefreshSession() - .subscribe((result) => { + .subscribe((result: any) => { expect(result).toBe(null); }); })); @@ -542,7 +542,7 @@ describe('RefreshSessionService ', () => { spyOn( refreshSessionRefreshTokenService, 'refreshSessionWithRefreshTokens' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); (refreshSessionService as any) .startRefreshSession(allConfigs[0], allConfigs) @@ -573,7 +573,7 @@ describe('RefreshSessionService ', () => { const refreshSessionWithRefreshTokensSpy = spyOn( refreshSessionRefreshTokenService, 'refreshSessionWithRefreshTokens' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); (refreshSessionService as any) .startRefreshSession(allConfigs[0], allConfigs) @@ -604,12 +604,12 @@ describe('RefreshSessionService ', () => { const refreshSessionWithRefreshTokensSpy = spyOn( refreshSessionRefreshTokenService, 'refreshSessionWithRefreshTokens' - ).and.returnValue(of(null)); + ).and.returnValue(of({} as CallbackContext)); const refreshSessionWithIframeSpy = spyOn( refreshSessionIframeService, 'refreshSessionWithIframe' - ).and.returnValue(of(null)); + ).and.returnValue(of(false)); (refreshSessionService as any) .startRefreshSession(allConfigs[0], allConfigs) diff --git a/projects/angular-auth-oidc-client/src/lib/config/config.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/config/config.service.spec.ts index 075c2a6d..4fd914d4 100644 --- a/projects/angular-auth-oidc-client/src/lib/config/config.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/config/config.service.spec.ts @@ -165,7 +165,7 @@ describe('Configuration Service', () => { }); configService.getOpenIDConfiguration('configId1').subscribe((config) => { - expect(config.authWellknownEndpoints).toEqual({ + expect(config?.authWellknownEndpoints).toEqual({ issuer: 'auth-well-known', }); }); @@ -214,9 +214,12 @@ describe('Configuration Service', () => { EventTypes.ConfigLoaded, jasmine.anything() ); - expect(storeWellKnownEndpointsSpy).toHaveBeenCalledOnceWith(config, { - issuer: 'auth-well-known', - }); + expect(storeWellKnownEndpointsSpy).toHaveBeenCalledOnceWith( + config as OpenIdConfiguration, + { + issuer: 'auth-well-known', + } + ); }); })); }); @@ -255,7 +258,7 @@ describe('Configuration Service', () => { expect(allConfigIds).toEqual(['0-clientId1', '1-clientId2']); expect(result.currentConfig).toBeTruthy(); - expect(result.currentConfig.configId).toBeTruthy(); + expect(result.currentConfig?.configId).toBeTruthy(); }); })); diff --git a/projects/angular-auth-oidc-client/src/lib/config/validation/config-validation.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/config/validation/config-validation.service.spec.ts index 6a8cee75..d9dc7fef 100644 --- a/projects/angular-auth-oidc-client/src/lib/config/validation/config-validation.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/config/validation/config-validation.service.spec.ts @@ -2,6 +2,7 @@ import { TestBed } from '@angular/core/testing'; import { mockClass } from '../../../test/auto-mock'; import { LogLevel } from '../../logging/log-level'; import { LoggerService } from '../../logging/logger.service'; +import { OpenIdConfiguration } from '../openid-configuration'; import { ConfigValidationService } from './config-validation.service'; import { allMultipleConfigRules } from './rules'; @@ -71,7 +72,7 @@ describe('Config Validation Service', () => { describe('ensure-clientId.rule', () => { it('return false when no clientId is set', () => { - const config = { ...VALID_CONFIG, clientId: null }; + const config = { ...VALID_CONFIG, clientId: '' } as OpenIdConfiguration; const result = configValidationService.validateConfig(config); expect(result).toBeFalse(); @@ -80,7 +81,10 @@ describe('Config Validation Service', () => { describe('ensure-authority-server.rule', () => { it('return false when no security token service is set', () => { - const config = { ...VALID_CONFIG, authority: null }; + const config = { + ...VALID_CONFIG, + authority: '', + } as OpenIdConfiguration; const result = configValidationService.validateConfig(config); expect(result).toBeFalse(); @@ -102,8 +106,8 @@ describe('Config Validation Service', () => { ...VALID_CONFIG, silentRenew: true, useRefreshToken: false, - silentRenewUrl: null, - }; + silentRenewUrl: '', + } as OpenIdConfiguration; const result = configValidationService.validateConfig(config); expect(result).toBeFalse(); @@ -169,7 +173,7 @@ describe('Config Validation Service', () => { const loggerErrorSpy = spyOn(loggerService, 'logError'); const loggerWarningSpy = spyOn(loggerService, 'logWarning'); - const result = configValidationService.validateConfigs([null]); + const result = configValidationService.validateConfigs([]); expect(result).toBeFalse(); expect(loggerWarningSpy).not.toHaveBeenCalled(); @@ -187,7 +191,7 @@ describe('Config Validation Service', () => { 'validateConfigsInternal' ).and.callThrough(); - const result = configValidationService.validateConfigs(null); + const result = configValidationService.validateConfigs([]); expect(result).toBeTrue(); expect(spy).toHaveBeenCalledOnceWith([], allMultipleConfigRules); From bdc7bff5cdb71993f855826e4b55d3e0367b0a36 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Thu, 4 Jan 2024 11:05:23 +0100 Subject: [PATCH 20/56] Fix test assertions and parameter in popup service --- .../src/lib/auth-state/auth-state.service.spec.ts | 2 +- .../src/lib/config/config.service.spec.ts | 4 ++-- .../src/lib/config/config.service.ts | 4 ++-- .../lib/config/validation/config-validation.service.ts | 6 +++++- .../history-jwt-keys-callback-handler.service.spec.ts | 1 + .../src/lib/flows/flows.service.spec.ts | 8 ++++---- .../src/lib/login/popup/popup.service.spec.ts | 2 +- 7 files changed, 16 insertions(+), 11 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.spec.ts index c8ff7b4e..e4db1c02 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.spec.ts @@ -348,7 +348,7 @@ describe('Auth State Service', () => { configId: 'configId1', }); - expect(result).toBe(null); + expect(result).toBe({}); }); it('isAuthorized is true returns object', () => { diff --git a/projects/angular-auth-oidc-client/src/lib/config/config.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/config/config.service.spec.ts index 4fd914d4..55982128 100644 --- a/projects/angular-auth-oidc-client/src/lib/config/config.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/config/config.service.spec.ts @@ -262,7 +262,7 @@ describe('Configuration Service', () => { }); })); - it(`returns null if config is not valid`, waitForAsync(() => { + it(`returns empty array if config is not valid`, waitForAsync(() => { spyOn(stsConfigLoader, 'loadConfigs').and.returnValue( of([ { configId: 'configId1' } as OpenIdConfiguration, @@ -275,7 +275,7 @@ describe('Configuration Service', () => { configService .getOpenIDConfigurations() .subscribe(({ allConfigs, currentConfig }) => { - expect(allConfigs).toBeNull(); + expect(allConfigs).toEqual([]); expect(currentConfig).toBeNull(); }); })); diff --git a/projects/angular-auth-oidc-client/src/lib/config/config.service.ts b/projects/angular-auth-oidc-client/src/lib/config/config.service.ts index 54362276..ba0934ac 100644 --- a/projects/angular-auth-oidc-client/src/lib/config/config.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/config/config.service.ts @@ -98,8 +98,8 @@ export class ConfigurationService { const allHandleConfigs$ = passedConfigs.map((x) => this.handleConfig(x)); const as = forkJoin(allHandleConfigs$).pipe( - map((x) => x.filter((y) => Boolean(y))), - map((z) => z as OpenIdConfiguration[]) + map((config) => config.filter((conf) => Boolean(conf))), + map((c) => c as OpenIdConfiguration[]) ); return as; diff --git a/projects/angular-auth-oidc-client/src/lib/config/validation/config-validation.service.ts b/projects/angular-auth-oidc-client/src/lib/config/validation/config-validation.service.ts index e0395c22..0260c161 100644 --- a/projects/angular-auth-oidc-client/src/lib/config/validation/config-validation.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/config/validation/config-validation.service.ts @@ -2,7 +2,7 @@ import { Injectable } from '@angular/core'; import { LoggerService } from '../../logging/logger.service'; import { OpenIdConfiguration } from '../openid-configuration'; import { Level, RuleValidationResult } from './rule'; -import { allRules, allMultipleConfigRules } from './rules'; +import { allMultipleConfigRules, allRules } from './rules'; @Injectable({ providedIn: 'root' }) export class ConfigValidationService { @@ -23,6 +23,10 @@ export class ConfigValidationService { passedConfigs: OpenIdConfiguration[], allRulesToUse: any[] ): boolean { + if (passedConfigs.length === 0) { + return false; + } + const allValidationResults = allRulesToUse.map((rule) => rule(passedConfigs) ); diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/history-jwt-keys-callback-handler.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/history-jwt-keys-callback-handler.service.spec.ts index 575aa1c3..8e782da5 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/history-jwt-keys-callback-handler.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/history-jwt-keys-callback-handler.service.spec.ts @@ -392,6 +392,7 @@ describe('HistoryJwtKeysCallbackHandlerService', () => { it('calls authStateService.updateAndPublishAuthState with login required if the error is `login_required`', waitForAsync(() => { const callbackContext = { authResult: { error: 'login_required' }, + isRenewProcess: false, } as CallbackContext; const allconfigs = [ { diff --git a/projects/angular-auth-oidc-client/src/lib/flows/flows.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/flows.service.spec.ts index c79a0f79..e81e4da4 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/flows.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/flows.service.spec.ts @@ -115,7 +115,7 @@ describe('Flows Service', () => { service .processCodeFlowCallback('some-url1234', allConfigs[0], allConfigs) .subscribe((value) => { - expect(value).toBeNull(); + expect(value).toEqual({} as CallbackContext); expect(codeFlowCallbackSpy).toHaveBeenCalledOnceWith( 'some-url1234', allConfigs[0] @@ -159,7 +159,7 @@ describe('Flows Service', () => { allConfigs ) .subscribe((value) => { - expect(value).toBeNull(); + expect(value).toEqual({} as CallbackContext); expect(codeFlowCodeRequestSpy).toHaveBeenCalled(); expect(callbackHistoryAndResetJwtKeysSpy).toHaveBeenCalled(); expect(callbackStateValidationSpy).toHaveBeenCalled(); @@ -195,7 +195,7 @@ describe('Flows Service', () => { service .processImplicitFlowCallback(allConfigs[0], allConfigs, 'any-hash') .subscribe((value) => { - expect(value).toBeNull(); + expect(value).toEqual({} as CallbackContext); expect(implicitFlowCallbackSpy).toHaveBeenCalled(); expect(callbackHistoryAndResetJwtKeysSpy).toHaveBeenCalled(); expect(callbackStateValidationSpy).toHaveBeenCalled(); @@ -235,7 +235,7 @@ describe('Flows Service', () => { service .processRefreshToken(allConfigs[0], allConfigs) .subscribe((value) => { - expect(value).toBeNull(); + expect(value).toEqual({} as CallbackContext); expect(refreshSessionWithRefreshTokensSpy).toHaveBeenCalled(); expect(refreshTokensRequestTokensSpy).toHaveBeenCalled(); expect(callbackHistoryAndResetJwtKeysSpy).toHaveBeenCalled(); diff --git a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts index 79eacd36..c44bf077 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts @@ -252,7 +252,7 @@ describe('PopUpService', () => { })); it('user closed', fakeAsync(() => { - popUpService.openPopUp('url', {}, { configId: 'configId1' }); + popUpService.openPopUp('url', undefined, { configId: 'configId1' }); expect(popupResult).toBeUndefined(); expect(cleanUpSpy).not.toHaveBeenCalled(); From 33d69fa5087aa2bbe10405f4aa4f84c4ca61d552 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Thu, 4 Jan 2024 12:01:03 +0100 Subject: [PATCH 21/56] Fix unit test failures in auth-state and url services --- .../lib/auth-state/auth-state.service.spec.ts | 2 +- .../lib/auth-state/check-auth.service.spec.ts | 1 + .../src/lib/utils/url/url.service.spec.ts | 32 +++++++------------ .../src/lib/utils/url/url.service.ts | 16 +++++----- 4 files changed, 21 insertions(+), 30 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.spec.ts index e4db1c02..2ecf471b 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.spec.ts @@ -348,7 +348,7 @@ describe('Auth State Service', () => { configId: 'configId1', }); - expect(result).toBe({}); + expect(result).toEqual({}); }); it('isAuthorized is true returns object', () => { diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts index e42ef9e8..a42282f9 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts @@ -226,6 +226,7 @@ describe('CheckAuthService', () => { userData: null, idToken: '', accessToken: '', + configId: '', }); expect(popupSpy).toHaveBeenCalled(); }); diff --git a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.spec.ts index 1d3b951b..206c7be3 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.spec.ts @@ -165,7 +165,7 @@ describe('UrlService Tests', () => { }); describe('createAuthorizeUrl', () => { - it('returns null when no authoizationendpoint given -> wellKnownEndpoints null', () => { + it('returns empty string when no authoizationendpoint given -> wellKnownEndpoints null', () => { const value = (service as any).createAuthorizeUrl( '', // Implicit Flow 'https://localhost:44386', @@ -173,12 +173,10 @@ describe('UrlService Tests', () => { 'state' ); - const expectValue = null; - - expect(value).toEqual(expectValue); + expect(value).toEqual(''); }); - it('returns null when no authoizationendpoint given -> configurationProvider null', () => { + it('returns empty string when no authoizationendpoint given -> configurationProvider null', () => { (service as any).configurationProvider = null; const value = (service as any).createAuthorizeUrl( @@ -188,12 +186,10 @@ describe('UrlService Tests', () => { 'state' ); - const expectValue = null; - - expect(value).toEqual(expectValue); + expect(value).toEqual(''); }); - it('returns null when clientId is null', () => { + it('returns empty string when clientId is null', () => { const config = { configId: 'configId1', clientId: '' }; const authorizationEndpoint = 'authorizationEndpoint'; @@ -209,12 +205,10 @@ describe('UrlService Tests', () => { config ); - const expectValue = null; - - expect(value).toEqual(expectValue); + expect(value).toEqual(''); }); - it('returns null when responseType is null', () => { + it('returns empty string when responseType is null', () => { const config = { configId: 'configId1', clientId: 'something', @@ -234,12 +228,10 @@ describe('UrlService Tests', () => { config ); - const expectValue = null; - - expect(value).toEqual(expectValue); + expect(value).toEqual(''); }); - it('returns null when scope is null', () => { + it('returns empty string when scope is null', () => { const config = { configId: 'configId1', clientId: 'something', @@ -260,9 +252,7 @@ describe('UrlService Tests', () => { config ); - const expectValue = null; - - expect(value).toEqual(expectValue); + expect(value).toEqual(''); }); it('createAuthorizeUrl with code flow and codeChallenge adds "code_challenge" and "code_challenge_method" param', () => { @@ -1561,7 +1551,7 @@ describe('UrlService Tests', () => { const resultObs$ = serviceAsAny.createUrlCodeFlowWithSilentRenew(config); resultObs$.subscribe((result: any) => { - expect(result).toBe(null); + expect(result).toBe(''); }); })); }); diff --git a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts index e10dd710..fbeea91f 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts @@ -431,7 +431,7 @@ export class UrlService { configuration: OpenIdConfiguration, prompt?: string, customRequestParams?: { [key: string]: string | number | boolean } - ): string | null { + ): string { const authWellKnownEndPoints = this.storagePersistenceService.read( 'authWellKnownEndPoints', configuration @@ -444,7 +444,7 @@ export class UrlService { `Can not create an authorize URL when authorizationEndpoint is '${authorizationEndpoint}'` ); - return null; + return ''; } const { clientId, responseType, scope, hdParam, customParamsAuthRequest } = @@ -457,7 +457,7 @@ export class UrlService { clientId ); - return null; + return ''; } if (!responseType) { @@ -467,7 +467,7 @@ export class UrlService { responseType ); - return null; + return ''; } if (!scope) { @@ -477,7 +477,7 @@ export class UrlService { scope ); - return null; + return ''; } const urlParts = authorizationEndpoint.split('?'); @@ -564,7 +564,7 @@ export class UrlService { private createUrlCodeFlowWithSilentRenew( configuration: OpenIdConfiguration, customParams?: { [key: string]: string | number | boolean } - ): Observable { + ): Observable { const state = this.flowsDataService.getExistingOrCreateAuthStateControl(configuration); const nonce = this.flowsDataService.createNonce(configuration); @@ -583,7 +583,7 @@ export class UrlService { const silentRenewUrl = this.getSilentRenewUrl(configuration); if (!silentRenewUrl) { - return null; + return ''; } const authWellKnownEndPoints = this.storagePersistenceService.read( @@ -608,7 +608,7 @@ export class UrlService { 'authWellKnownEndpoints is undefined' ); - return null; + return ''; }) ); } From 80829e74ea495a2c4eb8cba29d76a735101c3773 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Thu, 4 Jan 2024 12:48:09 +0100 Subject: [PATCH 22/56] Refactor URL service to simplify code --- .../src/lib/utils/url/url.service.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts index fbeea91f..ee1e290e 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts @@ -492,10 +492,7 @@ export class UrlService { params = params.append('nonce', nonce); params = params.append('state', state); - if ( - this.flowHelper.isCurrentFlowCodeFlow(configuration) && - Boolean(codeChallenge) - ) { + if (this.flowHelper.isCurrentFlowCodeFlow(configuration)) { params = params.append('code_challenge', codeChallenge); params = params.append('code_challenge_method', 'S256'); } From 80c876f0e2703c7c0af1363466320aa7b5b046a3 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Fri, 26 Jan 2024 09:09:08 +0100 Subject: [PATCH 23/56] Fix CheckAuthService configuration issue --- .../lib/auth-state/check-auth.service.spec.ts | 49 ++++++++++--------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts index a42282f9..6611db8b 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts @@ -15,6 +15,7 @@ import { CallbackContext } from '../flows/callback-context'; import { CheckSessionService } from '../iframe/check-session.service'; import { SilentRenewService } from '../iframe/silent-renew.service'; import { LoggerService } from '../logging/logger.service'; +import { LoginResponse } from '../login/login-response'; import { PopUpService } from '../login/popup/popup.service'; import { EventTypes } from '../public-events/event-types'; import { PublicEventsService } from '../public-events/public-events.service'; @@ -183,24 +184,6 @@ describe('CheckAuthService', () => { }); })); - it('returns isAuthenticated: false with error message when config is not valid', waitForAsync(() => { - const allConfigs: OpenIdConfiguration[] = []; - - checkAuthService - .checkAuth(allConfigs[0], allConfigs) - .subscribe((result) => - expect(result).toEqual({ - isAuthenticated: false, - errorMessage: - 'Please provide at least one configuration before setting up the module', - configId: '', - idToken: '', - userData: null, - accessToken: '', - }) - ); - })); - it('returns null and sendMessageToMainWindow if currently in a popup', waitForAsync(() => { const allConfigs = [ { configId: 'configId1', authority: 'some-authority' }, @@ -326,9 +309,17 @@ describe('CheckAuthService', () => { spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( true ); + spyOn(currentUrlService, 'getCurrentUrl').and.returnValue( + 'http://localhost:4200' + ); spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( of({} as CallbackContext) ); + spyOn(userService, 'getUserDataFromStore').and.returnValue({ + some: 'user-data', + }); + spyOn(authStateService, 'getAccessToken').and.returnValue('at'); + spyOn(authStateService, 'getIdToken').and.returnValue('idt'); const setAuthorizedAndFireEventSpy = spyOn( authStateService, @@ -341,10 +332,12 @@ describe('CheckAuthService', () => { .subscribe((result) => { expect(result).toEqual({ isAuthenticated: true, - userData: undefined, - accessToken: '', + userData: { + some: 'user-data', + }, + accessToken: 'at', configId: 'configId1', - idToken: '', + idToken: 'idt', }); expect(setAuthorizedAndFireEventSpy).toHaveBeenCalled(); expect(userServiceSpy).toHaveBeenCalled(); @@ -415,9 +408,10 @@ describe('CheckAuthService', () => { { configId: 'configId1', authority: 'some-authority' }, ]; - spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( - of({} as CallbackContext) + spyOn(currentUrlService, 'getCurrentUrl').and.returnValue( + 'http://localhost:4200' ); + spyOn(callBackService, 'isCallback').and.returnValue(false); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( true ); @@ -555,6 +549,12 @@ describe('CheckAuthService', () => { const allConfigs = [ { configId: 'configId1', authority: 'some-authority' }, ]; + spyOn(currentUrlService, 'getCurrentUrl').and.returnValue( + 'http://localhost:4200' + ); + spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( + true + ); const fireEventSpy = spyOn(publicEventsService, 'fireEvent'); checkAuthService.checkAuth(allConfigs[0], allConfigs).subscribe(() => { @@ -597,6 +597,9 @@ describe('CheckAuthService', () => { spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( true ); + spyOn(refreshSessionService, 'forceRefreshSession').and.returnValue( + of({ isAuthenticated: true } as LoginResponse) + ); spyOn(silentRenewService, 'isSilentRenewConfigured').and.returnValue( true From d9d48915ca9314a5e3a4f98ad93dc7f5a0f7caac Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Fri, 26 Jan 2024 09:12:27 +0100 Subject: [PATCH 24/56] Fix unit test failures and code cleanup --- .../src/lib/auth-state/check-auth.service.spec.ts | 2 ++ .../src/lib/login/popup/popup.service.spec.ts | 8 ++++++-- .../src/lib/public-events/event-types.ts | 1 - projects/angular-auth-oidc-client/src/test/auto-mock.ts | 5 +++-- 4 files changed, 11 insertions(+), 5 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts index 6611db8b..c12c37fd 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts @@ -549,12 +549,14 @@ describe('CheckAuthService', () => { const allConfigs = [ { configId: 'configId1', authority: 'some-authority' }, ]; + spyOn(currentUrlService, 'getCurrentUrl').and.returnValue( 'http://localhost:4200' ); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( true ); + const fireEventSpy = spyOn(publicEventsService, 'fireEvent'); checkAuthService.checkAuth(allConfigs[0], allConfigs).subscribe(() => { diff --git a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts index c44bf077..002f2928 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts @@ -205,7 +205,9 @@ describe('PopUpService', () => { }); it('message received with data', fakeAsync(() => { - let listener: (event: MessageEvent) => void = () => {}; + let listener: (event: MessageEvent) => void = () => { + return; + }; spyOn(window, 'addEventListener').and.callFake( (_: any, func: any) => (listener = func) @@ -230,7 +232,9 @@ describe('PopUpService', () => { })); it('message received without data does return but cleanup does not throw event', fakeAsync(() => { - let listener: (event: MessageEvent) => void = () => {}; + let listener: (event: MessageEvent) => void = () => { + return; + }; spyOn(window, 'addEventListener').and.callFake( (_: any, func: any) => (listener = func) diff --git a/projects/angular-auth-oidc-client/src/lib/public-events/event-types.ts b/projects/angular-auth-oidc-client/src/lib/public-events/event-types.ts index 7663fde3..54f35a95 100644 --- a/projects/angular-auth-oidc-client/src/lib/public-events/event-types.ts +++ b/projects/angular-auth-oidc-client/src/lib/public-events/event-types.ts @@ -1,4 +1,3 @@ -// eslint-disable-next-line no-shadow export enum EventTypes { /** * This only works in the AppModule Constructor diff --git a/projects/angular-auth-oidc-client/src/test/auto-mock.ts b/projects/angular-auth-oidc-client/src/test/auto-mock.ts index 956e8dd9..30fe03be 100644 --- a/projects/angular-auth-oidc-client/src/test/auto-mock.ts +++ b/projects/angular-auth-oidc-client/src/test/auto-mock.ts @@ -12,9 +12,10 @@ export function mockClass(obj: new (...args: any[]) => T): any { const mockedClass = class T {}; allMethods.forEach( - // eslint-disable-next-line @typescript-eslint/no-empty-function (method: string) => - ((mockedClass.prototype as any)[method] = (): void => {}) + ((mockedClass.prototype as any)[method] = (): void => { + return; + }) ); allProperties.forEach((method) => { From 9deb5d06bdda2b7080114d1ebcfdd0b206b9258e Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Sat, 27 Jan 2024 18:37:42 +0100 Subject: [PATCH 25/56] Fix config validation and callback handling in unit tests --- .../lib/config/validation/config-validation.service.spec.ts | 5 ----- .../history-jwt-keys-callback-handler.service.spec.ts | 1 + .../src/lib/login/popup/popup.service.spec.ts | 6 +++--- 3 files changed, 4 insertions(+), 8 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/config/validation/config-validation.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/config/validation/config-validation.service.spec.ts index d9dc7fef..8ba77a5e 100644 --- a/projects/angular-auth-oidc-client/src/lib/config/validation/config-validation.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/config/validation/config-validation.service.spec.ts @@ -170,17 +170,12 @@ describe('Config Validation Service', () => { }); it('should return false and a better error message when config is not passed as object with config property', () => { - const loggerErrorSpy = spyOn(loggerService, 'logError'); const loggerWarningSpy = spyOn(loggerService, 'logWarning'); const result = configValidationService.validateConfigs([]); expect(result).toBeFalse(); expect(loggerWarningSpy).not.toHaveBeenCalled(); - expect(loggerErrorSpy.calls.argsFor(0)).toEqual([ - null, - `Please make sure you add an object with a 'config' property: ....({ config }) instead of ...(config)`, - ]); }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/history-jwt-keys-callback-handler.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/history-jwt-keys-callback-handler.service.spec.ts index 8e782da5..0a26cea9 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/history-jwt-keys-callback-handler.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/history-jwt-keys-callback-handler.service.spec.ts @@ -352,6 +352,7 @@ describe('HistoryJwtKeysCallbackHandlerService', () => { it('calls resetAuthorizationData, resets nonce and authStateService in case of an error', waitForAsync(() => { const callbackContext = { authResult: { error: 'someError' }, + isRenewProcess: false, } as CallbackContext; const allconfigs = [ { diff --git a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts index 002f2928..6a6a86ee 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts @@ -215,7 +215,7 @@ describe('PopUpService', () => { popUpService.openPopUp('url', {}, { configId: 'configId1' }); - expect(popupResult).toBeUndefined(); + expect(popupResult).toEqual({} as PopupResult); expect(cleanUpSpy).not.toHaveBeenCalled(); listener(new MessageEvent('message', { data: 'some-url1111' })); @@ -243,14 +243,14 @@ describe('PopUpService', () => { popUpService.openPopUp('url', {}, { configId: 'configId1' }); - expect(popupResult).toBeUndefined(); + expect(popupResult).toEqual({} as PopupResult); expect(cleanUpSpy).not.toHaveBeenCalled(); listener(new MessageEvent('message', { data: null })); tick(200); - expect(popupResult).toBeUndefined(); + expect(popupResult).toEqual({} as PopupResult); expect(cleanUpSpy).toHaveBeenCalled(); expect(nextSpy).not.toHaveBeenCalled(); })); From ac134c1fae523135ad2ae890d0976e166badc20f Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Sat, 27 Jan 2024 18:39:46 +0100 Subject: [PATCH 26/56] Fix validation test and update popup service test --- .../src/lib/config/validation/config-validation.service.spec.ts | 2 +- .../src/lib/login/popup/popup.service.spec.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/config/validation/config-validation.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/config/validation/config-validation.service.spec.ts index 8ba77a5e..45646377 100644 --- a/projects/angular-auth-oidc-client/src/lib/config/validation/config-validation.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/config/validation/config-validation.service.spec.ts @@ -188,7 +188,7 @@ describe('Config Validation Service', () => { const result = configValidationService.validateConfigs([]); - expect(result).toBeTrue(); + expect(result).toBeFalse(); expect(spy).toHaveBeenCalledOnceWith([], allMultipleConfigRules); }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts index 6a6a86ee..f3e5214b 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts @@ -258,7 +258,7 @@ describe('PopUpService', () => { it('user closed', fakeAsync(() => { popUpService.openPopUp('url', undefined, { configId: 'configId1' }); - expect(popupResult).toBeUndefined(); + expect(popupResult).toEqual({} as PopupResult); expect(cleanUpSpy).not.toHaveBeenCalled(); (popup as any).closed = true; From 4e19c7dcc1971f9b9647792ab7e39b3015f03ec7 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Sat, 27 Jan 2024 18:48:11 +0100 Subject: [PATCH 27/56] Fix CheckAuthService test cases --- .../lib/auth-state/check-auth.service.spec.ts | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts index c12c37fd..008a58f3 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts @@ -192,6 +192,9 @@ describe('CheckAuthService', () => { spyOn(popUpService as any, 'canAccessSessionStorage').and.returnValue( true ); + spyOn(currentUrlService, 'getCurrentUrl').and.returnValue( + 'http://localhost:4200' + ); spyOnProperty(popUpService as any, 'windowInternal').and.returnValue({ opener: {} as Window, }); @@ -253,6 +256,7 @@ describe('CheckAuthService', () => { spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( true ); + const spy = spyOn( callBackService, 'handleCallbackAndFireEvents' @@ -285,6 +289,9 @@ describe('CheckAuthService', () => { callBackService, 'handleCallbackAndFireEvents' ).and.returnValue(of({} as CallbackContext)); + spyOn(currentUrlService, 'getCurrentUrl').and.returnValue( + 'http://localhost:4200' + ); checkAuthService .checkAuth(allConfigs[0], allConfigs) @@ -427,7 +434,9 @@ describe('CheckAuthService', () => { const allConfigs = [ { configId: 'configId1', authority: 'some-authority' }, ]; - + spyOn(currentUrlService, 'getCurrentUrl').and.returnValue( + 'http://localhost:4200' + ); spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( of({} as CallbackContext) ); @@ -455,7 +464,9 @@ describe('CheckAuthService', () => { spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( true ); - + spyOn(currentUrlService, 'getCurrentUrl').and.returnValue( + 'http://localhost:4200' + ); const spy = spyOn( periodicallyTokenCheckService, 'startTokenValidationPeriodically' @@ -495,6 +506,9 @@ describe('CheckAuthService', () => { spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( of({} as CallbackContext) ); + spyOn(currentUrlService, 'getCurrentUrl').and.returnValue( + 'http://localhost:4200' + ); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( true ); From c4b4611e8149fd54820fce650582f00db01d0b01 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Sat, 27 Jan 2024 18:59:32 +0100 Subject: [PATCH 28/56] Fix CheckAuthService test cases --- .../src/lib/auth-state/check-auth.service.spec.ts | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts index 008a58f3..56d92245 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts @@ -360,9 +360,14 @@ describe('CheckAuthService', () => { spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( false ); + spyOn(authStateService, 'getAccessToken').and.returnValue('at'); + spyOn(authStateService, 'getIdToken').and.returnValue('it'); spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( of({} as CallbackContext) ); + spyOn(currentUrlService, 'getCurrentUrl').and.returnValue( + 'http://localhost:4200' + ); const setAuthorizedAndFireEventSpy = spyOn( authStateService, @@ -376,9 +381,9 @@ describe('CheckAuthService', () => { expect(result).toEqual({ isAuthenticated: false, userData: undefined, - accessToken: '', + accessToken: 'at', configId: 'configId1', - idToken: '', + idToken: 'it', }); expect(setAuthorizedAndFireEventSpy).not.toHaveBeenCalled(); expect(userServiceSpy).not.toHaveBeenCalled(); @@ -485,6 +490,9 @@ describe('CheckAuthService', () => { spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( of({} as CallbackContext) ); + spyOn(currentUrlService, 'getCurrentUrl').and.returnValue( + 'http://localhost:4200' + ); spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( true ); @@ -527,6 +535,9 @@ describe('CheckAuthService', () => { { configId: 'configId1', authority: 'some-authority' }, ]; + spyOn(currentUrlService, 'getCurrentUrl').and.returnValue( + 'http://localhost:4200' + ); spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( of({} as CallbackContext) ); From cdece08a452d38bdaa2483ce20548a5cd972ddf8 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Sat, 27 Jan 2024 19:04:06 +0100 Subject: [PATCH 29/56] Fix getCurrentUrl() in CheckAuthService.spec.ts --- .../lib/auth-state/check-auth.service.spec.ts | 30 +++++++++++++++---- 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts index 56d92245..5c6ae0ba 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts @@ -231,6 +231,9 @@ describe('CheckAuthService', () => { callBackService, 'handleCallbackAndFireEvents' ).and.returnValue(throwError(() => new Error('ERROR'))); + spyOn(currentUrlService, 'getCurrentUrl').and.returnValue( + 'http://localhost:4200' + ); checkAuthService .checkAuth(allConfigs[0], allConfigs) @@ -256,6 +259,11 @@ describe('CheckAuthService', () => { spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( true ); + spyOn(currentUrlService, 'getCurrentUrl').and.returnValue( + 'http://localhost:4200' + ); + spyOn(authStateService, 'getAccessToken').and.returnValue('at'); + spyOn(authStateService, 'getIdToken').and.returnValue('idt'); const spy = spyOn( callBackService, @@ -268,9 +276,9 @@ describe('CheckAuthService', () => { expect(result).toEqual({ isAuthenticated: true, userData: undefined, - accessToken: '', + accessToken: 'at', configId: 'configId1', - idToken: '', + idToken: 'idt', }); expect(spy).toHaveBeenCalled(); }); @@ -292,6 +300,8 @@ describe('CheckAuthService', () => { spyOn(currentUrlService, 'getCurrentUrl').and.returnValue( 'http://localhost:4200' ); + spyOn(authStateService, 'getAccessToken').and.returnValue('at'); + spyOn(authStateService, 'getIdToken').and.returnValue('idt'); checkAuthService .checkAuth(allConfigs[0], allConfigs) @@ -299,9 +309,9 @@ describe('CheckAuthService', () => { expect(result).toEqual({ isAuthenticated: true, userData: undefined, - accessToken: '', + accessToken: 'at', configId: 'configId1', - idToken: '', + idToken: 'idt', }); expect(spy).not.toHaveBeenCalled(); }); @@ -395,6 +405,11 @@ describe('CheckAuthService', () => { { configId: 'configId1', authority: 'some-authority' }, ]; + spyOn(currentUrlService, 'getCurrentUrl').and.returnValue( + 'http://localhost:4200' + ); + spyOn(authStateService, 'getAccessToken').and.returnValue('at'); + spyOn(authStateService, 'getIdToken').and.returnValue('idt'); spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( of({} as CallbackContext) ); @@ -408,9 +423,9 @@ describe('CheckAuthService', () => { expect(result).toEqual({ isAuthenticated: true, userData: undefined, - accessToken: '', + accessToken: 'at', configId: 'configId1', - idToken: '', + idToken: 'idt', }); }); })); @@ -602,6 +617,9 @@ describe('CheckAuthService', () => { spyOn(callBackService, 'handleCallbackAndFireEvents').and.returnValue( throwError(() => new Error('ERROR')) ); + spyOn(currentUrlService, 'getCurrentUrl').and.returnValue( + 'http://localhost:4200' + ); checkAuthService.checkAuth(allConfigs[0], allConfigs).subscribe(() => { expect(fireEventSpy.calls.allArgs()).toEqual([ From 653a4ba15bc275d1b57f9014415a76521ac8e9ee Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Sat, 27 Jan 2024 19:06:37 +0100 Subject: [PATCH 30/56] Fix existingIdToken assignment and update test expectation --- .../code-flow-callback-handler.service.spec.ts | 2 +- .../src/lib/login/popup/popup.service.spec.ts | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/code-flow-callback-handler.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/code-flow-callback-handler.service.spec.ts index f2ceddb6..fec93a98 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/code-flow-callback-handler.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/code-flow-callback-handler.service.spec.ts @@ -94,7 +94,7 @@ describe('CodeFlowCallbackHandlerService', () => { isRenewProcess: false, jwtKeys: null, validationResult: null, - existingIdToken: '', + existingIdToken: null, } as CallbackContext; service diff --git a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts index f3e5214b..d5fd7b8a 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts @@ -265,7 +265,10 @@ describe('PopUpService', () => { tick(200); - expect(popupResult).toEqual({ userClosed: true } as PopupResult); + expect(popupResult).toEqual({ + userClosed: true, + receivedUrl: '', + } as PopupResult); expect(cleanUpSpy).toHaveBeenCalled(); })); }); From d3f9d96d0bc05cb1fec9559d2673f82febbd8dd6 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Sat, 27 Jan 2024 19:09:02 +0100 Subject: [PATCH 31/56] Fix callback error handling and update configurations --- .../src/lib/auth-state/check-auth.service.spec.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts index 5c6ae0ba..5178bed5 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts @@ -227,10 +227,12 @@ describe('CheckAuthService', () => { spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( true ); + const spy = spyOn( callBackService, 'handleCallbackAndFireEvents' ).and.returnValue(throwError(() => new Error('ERROR'))); + spyOn(currentUrlService, 'getCurrentUrl').and.returnValue( 'http://localhost:4200' ); @@ -293,10 +295,12 @@ describe('CheckAuthService', () => { spyOn(authStateService, 'areAuthStorageTokensValid').and.returnValue( true ); + const spy = spyOn( callBackService, 'handleCallbackAndFireEvents' ).and.returnValue(of({} as CallbackContext)); + spyOn(currentUrlService, 'getCurrentUrl').and.returnValue( 'http://localhost:4200' ); @@ -454,6 +458,7 @@ describe('CheckAuthService', () => { const allConfigs = [ { configId: 'configId1', authority: 'some-authority' }, ]; + spyOn(currentUrlService, 'getCurrentUrl').and.returnValue( 'http://localhost:4200' ); From 50d68c7f87f9af38418689ae3babe0b5c5a7d494 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Sun, 28 Jan 2024 09:32:22 +0100 Subject: [PATCH 32/56] Fix configuration error in LoginService --- .../src/lib/login/login.service.spec.ts | 19 +++++++++++++++++++ .../src/lib/login/login.service.ts | 18 +++++------------- 2 files changed, 24 insertions(+), 13 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/login/login.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/login.service.spec.ts index df1d23b9..f3b52544 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/login.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/login.service.spec.ts @@ -75,6 +75,7 @@ describe('LoginService', () => { }); it('stores the customParams to the storage if customParams are given', () => { + // arrange const config = { usePushedAuthorisationRequests: false }; const storagePersistenceServiceSpy = spyOn( storagePersistenceService, @@ -90,6 +91,24 @@ describe('LoginService', () => { config ); }); + + it("should throw error if configuration is null and doesn't call loginPar or loginStandard", () => { + // arrange + const config = null; + const loginParSpy = spyOn(parLoginService, 'loginPar'); + const standardLoginSpy = spyOn(standardLoginService, 'loginStandard'); + const authOptions = { customParams: { custom: 'params' } }; + + // act + const fn = () => service.login(config, authOptions); + + // assert + expect(fn).toThrow( + new Error('Please provide a configuration before setting up the module') + ); + expect(loginParSpy).not.toHaveBeenCalled(); + expect(standardLoginSpy).not.toHaveBeenCalled(); + }); }); describe('loginWithPopUp', () => { diff --git a/projects/angular-auth-oidc-client/src/lib/login/login.service.ts b/projects/angular-auth-oidc-client/src/lib/login/login.service.ts index 6d8d4059..ca712a2d 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/login.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/login.service.ts @@ -1,5 +1,5 @@ import { Injectable } from '@angular/core'; -import { Observable, of, throwError } from 'rxjs'; +import { Observable, of } from 'rxjs'; import { AuthOptions } from '../auth-options'; import { OpenIdConfiguration } from '../config/openid-configuration'; import { StoragePersistenceService } from '../storage/storage-persistence.service'; @@ -25,14 +25,9 @@ export class LoginService { authOptions?: AuthOptions ): void { if (!configuration) { - throwError( - () => - new Error( - 'Please provide a configuration before setting up the module' - ) + throw new Error( + 'Please provide a configuration before setting up the module' ); - - return; } const { usePushedAuthorisationRequests } = configuration; @@ -62,11 +57,8 @@ export class LoginService { popupOptions?: PopupOptions ): Observable { if (!configuration) { - return throwError( - () => - new Error( - 'Please provide a configuration before setting up the module' - ) + throw new Error( + 'Please provide a configuration before setting up the module' ); } From e90ce9e0e2a591df2136c2133ce1e368e1c804ed Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Sun, 17 Mar 2024 14:59:40 +0100 Subject: [PATCH 33/56] Fix login service login function signature --- .../src/lib/login/login.service.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/projects/angular-auth-oidc-client/src/lib/login/login.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/login.service.spec.ts index f3b52544..7351ea96 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/login.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/login.service.spec.ts @@ -100,7 +100,7 @@ describe('LoginService', () => { const authOptions = { customParams: { custom: 'params' } }; // act - const fn = () => service.login(config, authOptions); + const fn = (): void => service.login(config, authOptions); // assert expect(fn).toThrow( From 282ba95fd135f0787c08dcdc96f912befed460f2 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Sun, 17 Mar 2024 15:46:40 +0100 Subject: [PATCH 34/56] Fix current URL service and URL service unit tests --- .../lib/utils/url/current-url.service.spec.ts | 20 +++++++---- .../src/lib/utils/url/current-url.service.ts | 5 +-- .../src/lib/utils/url/url.service.spec.ts | 34 +++++++++---------- .../src/lib/utils/url/url.service.ts | 16 ++++----- .../src/test/auto-mock.ts | 7 ++++ 5 files changed, 49 insertions(+), 33 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.spec.ts index 7e2755c7..0b6901ee 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.spec.ts @@ -4,23 +4,23 @@ import { CurrentUrlService } from './current-url.service'; describe('CurrentUrlService with existing Url', () => { let service: CurrentUrlService; + let document: any; + const documentValue = { + defaultView: { location: 'http://my-url.com?state=my-state' }, + }; beforeEach(() => { TestBed.configureTestingModule({ providers: [ - CurrentUrlService, { provide: DOCUMENT, - useValue: { - defaultView: { location: 'http://my-url.com?state=my-state' }, - }, + useValue: documentValue, }, ], }); - }); - beforeEach(() => { service = TestBed.inject(CurrentUrlService); + document = TestBed.inject(DOCUMENT); }); it('should create', () => { @@ -36,6 +36,14 @@ describe('CurrentUrlService with existing Url', () => { }); describe('getStateParamFromCurrentUrl', () => { + it('returns null if there is no current URL', () => { + spyOn(service, 'getCurrentUrl').and.returnValue(null); + + const stateParam = service.getStateParamFromCurrentUrl(''); + + expect(stateParam).toBe(null); + }); + it('returns the state param for the URL', () => { const stateParam = service.getStateParamFromCurrentUrl(); diff --git a/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.ts b/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.ts index cecdd266..a018c64e 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.ts @@ -1,9 +1,9 @@ import { DOCUMENT } from '@angular/common'; -import { Inject, Injectable } from '@angular/core'; +import { Injectable, inject } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class CurrentUrlService { - constructor(@Inject(DOCUMENT) private readonly document: Document) {} + private readonly document: Document = inject(DOCUMENT); getStateParamFromCurrentUrl(url?: string): string | null { const currentUrl = url || this.getCurrentUrl(); @@ -19,6 +19,7 @@ export class CurrentUrlService { } getCurrentUrl(): string | null { + console.log(this.document?.defaultView?.location); return this.document?.defaultView?.location.toString() ?? null; } } diff --git a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.spec.ts index 206c7be3..3be9d0cc 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.spec.ts @@ -1,6 +1,6 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { of } from 'rxjs'; -import { mockClass } from '../../../test/auto-mock'; +import { mockProvider } from '../../../test/auto-mock'; import { OpenIdConfiguration } from '../../config/openid-configuration'; import { FlowsDataService } from '../../flows/flows-data.service'; import { LoggerService } from '../../logging/logger.service'; @@ -21,23 +21,11 @@ describe('UrlService Tests', () => { TestBed.configureTestingModule({ providers: [ UrlService, - { - provide: LoggerService, - useClass: mockClass(LoggerService), - }, - { - provide: FlowsDataService, - useClass: mockClass(FlowsDataService), - }, + mockProvider(LoggerService), + mockProvider(FlowsDataService), FlowHelper, - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, - { - provide: JwtWindowCryptoService, - useClass: mockClass(JwtWindowCryptoService), - }, + mockProvider(StoragePersistenceService), + mockProvider(JwtWindowCryptoService), ], }); }); @@ -924,6 +912,12 @@ describe('UrlService Tests', () => { }); describe('getAuthorizeUrl', () => { + it('returns null if no config is given', waitForAsync(() => { + service.getAuthorizeUrl(null).subscribe((url) => { + expect(url).toBeNull(); + }); + })); + it('returns null if current flow is code flow and no redirect url is defined', waitForAsync(() => { spyOn(flowHelper, 'isCurrentFlowCodeFlow').and.returnValue(true); @@ -1793,6 +1787,12 @@ describe('UrlService Tests', () => { }); describe('getEndSessionUrl', () => { + it('returns null if no config given', () => { + const value = service.getEndSessionUrl(null); + + expect(value).toBeNull(); + }); + it('create URL when all parameters given', () => { //Arrange const config = { diff --git a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts index ee1e290e..9362d243 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts @@ -1,5 +1,5 @@ import { HttpParams } from '@angular/common/http'; -import { Injectable } from '@angular/core'; +import { Injectable, inject } from '@angular/core'; import { Observable, of } from 'rxjs'; import { map } from 'rxjs/operators'; import { AuthOptions } from '../../auth-options'; @@ -16,13 +16,13 @@ const AUTH0_ENDPOINT = 'auth0.com'; @Injectable({ providedIn: 'root' }) export class UrlService { - constructor( - private readonly loggerService: LoggerService, - private readonly flowsDataService: FlowsDataService, - private readonly flowHelper: FlowHelper, - private readonly storagePersistenceService: StoragePersistenceService, - private readonly jwtWindowCryptoService: JwtWindowCryptoService - ) {} + private readonly loggerService = inject(LoggerService); + private readonly flowsDataService = inject(FlowsDataService); + private readonly flowHelper = inject(FlowHelper); + private readonly storagePersistenceService = inject( + StoragePersistenceService + ); + private readonly jwtWindowCryptoService = inject(JwtWindowCryptoService); getUrlParameter(urlToCheck: string, name: string): string { if (!urlToCheck) { diff --git a/projects/angular-auth-oidc-client/src/test/auto-mock.ts b/projects/angular-auth-oidc-client/src/test/auto-mock.ts index 30fe03be..78c3a164 100644 --- a/projects/angular-auth-oidc-client/src/test/auto-mock.ts +++ b/projects/angular-auth-oidc-client/src/test/auto-mock.ts @@ -29,3 +29,10 @@ export function mockClass(obj: new (...args: any[]) => T): any { return mockedClass; } + +export function mockProvider(obj: new (...args: any[]) => T): any { + return { + provide: obj, + useClass: mockClass(obj), + }; +} From f7dcaac2d7d6b750565816774dc048be270b8b10 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Sun, 17 Mar 2024 17:33:26 +0100 Subject: [PATCH 35/56] Add AuthConfig unit test --- .../src/lib/auth-config.spec.ts | 15 +++++++++++++++ .../src/lib/utils/url/current-url.service.ts | 1 - 2 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 projects/angular-auth-oidc-client/src/lib/auth-config.spec.ts diff --git a/projects/angular-auth-oidc-client/src/lib/auth-config.spec.ts b/projects/angular-auth-oidc-client/src/lib/auth-config.spec.ts new file mode 100644 index 00000000..c639ac90 --- /dev/null +++ b/projects/angular-auth-oidc-client/src/lib/auth-config.spec.ts @@ -0,0 +1,15 @@ +import { PassedInitialConfig, createStaticLoader } from './auth-config'; + +describe('AuthConfig', () => { + describe('createStaticLoader', () => { + it('should throw an error if no config is provided', () => { + // Arrange + const passedConfig = {} as PassedInitialConfig; + // Act + // Assert + expect(() => createStaticLoader(passedConfig)).toThrowError( + 'No config provided!' + ); + }); + }); +}); diff --git a/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.ts b/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.ts index a018c64e..607d5f47 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.ts @@ -19,7 +19,6 @@ export class CurrentUrlService { } getCurrentUrl(): string | null { - console.log(this.document?.defaultView?.location); return this.document?.defaultView?.location.toString() ?? null; } } From 487b99570cf7441c3e489ac0aaece69b8af07cb1 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Sun, 17 Mar 2024 17:37:26 +0100 Subject: [PATCH 36/56] Refactor pre-commit hooks and fix linting issues --- lefthook.yml | 4 ++++ projects/angular-auth-oidc-client/src/lib/auth-config.spec.ts | 2 ++ .../src/lib/utils/url/current-url.service.spec.ts | 3 +-- .../angular-auth-oidc-client/src/lib/utils/url/url.service.ts | 4 ++++ 4 files changed, 11 insertions(+), 2 deletions(-) diff --git a/lefthook.yml b/lefthook.yml index e70b39d1..cfcc9684 100644 --- a/lefthook.yml +++ b/lefthook.yml @@ -10,9 +10,13 @@ pre-push: run: npm run fix-prettier {staged_files} pre-commit: + parallel: true commands: check-blockwords: run: npm run check-blockwords + + lint: + run: npm run lint-lib # # pre-commit: # parallel: true diff --git a/projects/angular-auth-oidc-client/src/lib/auth-config.spec.ts b/projects/angular-auth-oidc-client/src/lib/auth-config.spec.ts index c639ac90..c1e706da 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-config.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-config.spec.ts @@ -5,7 +5,9 @@ describe('AuthConfig', () => { it('should throw an error if no config is provided', () => { // Arrange const passedConfig = {} as PassedInitialConfig; + // Act + // Assert expect(() => createStaticLoader(passedConfig)).toThrowError( 'No config provided!' diff --git a/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.spec.ts index 0b6901ee..8122059d 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/url/current-url.service.spec.ts @@ -4,7 +4,7 @@ import { CurrentUrlService } from './current-url.service'; describe('CurrentUrlService with existing Url', () => { let service: CurrentUrlService; - let document: any; + const documentValue = { defaultView: { location: 'http://my-url.com?state=my-state' }, }; @@ -20,7 +20,6 @@ describe('CurrentUrlService with existing Url', () => { }); service = TestBed.inject(CurrentUrlService); - document = TestBed.inject(DOCUMENT); }); it('should create', () => { diff --git a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts index 9362d243..2e7bce5f 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/url/url.service.ts @@ -17,11 +17,15 @@ const AUTH0_ENDPOINT = 'auth0.com'; @Injectable({ providedIn: 'root' }) export class UrlService { private readonly loggerService = inject(LoggerService); + private readonly flowsDataService = inject(FlowsDataService); + private readonly flowHelper = inject(FlowHelper); + private readonly storagePersistenceService = inject( StoragePersistenceService ); + private readonly jwtWindowCryptoService = inject(JwtWindowCryptoService); getUrlParameter(urlToCheck: string, name: string): string { From 8e6f6e12e21d51542b40e9a60b2f09e5507f5d6c Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Mon, 18 Mar 2024 10:08:06 +0100 Subject: [PATCH 37/56] Refactor code to remove redundant assignments and imports --- angular.json | 372 ++++++++++++------ .../src/app/home/home.component.ts | 16 +- .../src/app/home/home.component.ts | 16 +- 3 files changed, 258 insertions(+), 146 deletions(-) diff --git a/angular.json b/angular.json index 418fb2a2..99239d49 100644 --- a/angular.json +++ b/angular.json @@ -36,7 +36,10 @@ "lint": { "builder": "@angular-eslint/builder:lint", "options": { - "lintFilePatterns": ["projects/angular-auth-oidc-client/**/*.ts", "projects/angular-auth-oidc-client/**/*.html"] + "lintFilePatterns": [ + "projects/angular-auth-oidc-client/**/*.ts", + "projects/angular-auth-oidc-client/**/*.html" + ] } } } @@ -110,14 +113,14 @@ "sslKey": "certs/dev_localhost.key", "sslCert": "certs/dev_localhost.pem", "port": 4200, - "buildTarget": "sample-code-flow-multi-iframe:build" + "browserTarget": "sample-code-flow-multi-iframe:build" }, "configurations": { "production": { - "buildTarget": "sample-code-flow-multi-iframe:build:production" + "browserTarget": "sample-code-flow-multi-iframe:build:production" }, "development": { - "buildTarget": "sample-code-flow-multi-iframe:build:development" + "browserTarget": "sample-code-flow-multi-iframe:build:development" } }, "defaultConfiguration": "development" @@ -125,7 +128,7 @@ "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { - "buildTarget": "sample-code-flow-multi-iframe:build" + "browserTarget": "sample-code-flow-multi-iframe:build" } }, "test": { @@ -135,7 +138,10 @@ "polyfills": "projects/sample-code-flow-multi-iframe/src/polyfills.ts", "tsConfig": "projects/sample-code-flow-multi-iframe/tsconfig.spec.json", "karmaConfig": "projects/sample-code-flow-multi-iframe/karma.conf.js", - "assets": ["projects/sample-code-flow-multi-iframe/src/favicon.ico", "projects/sample-code-flow-multi-iframe/src/assets"], + "assets": [ + "projects/sample-code-flow-multi-iframe/src/favicon.ico", + "projects/sample-code-flow-multi-iframe/src/assets" + ], "styles": ["projects/sample-code-flow-multi-iframe/src/styles.css"], "scripts": [] } @@ -143,7 +149,10 @@ "lint": { "builder": "@angular-eslint/builder:lint", "options": { - "lintFilePatterns": ["projects/sample-code-flow-multi-iframe/**/*.ts", "projects/sample-code-flow-multi-iframe/**/*.html"] + "lintFilePatterns": [ + "projects/sample-code-flow-multi-iframe/**/*.ts", + "projects/sample-code-flow-multi-iframe/**/*.html" + ] } } } @@ -216,14 +225,14 @@ "sslKey": "certs/dev_localhost.key", "sslCert": "certs/dev_localhost.pem", "port": 4204, - "buildTarget": "sample-code-flow-auto-login:build" + "browserTarget": "sample-code-flow-auto-login:build" }, "configurations": { "production": { - "buildTarget": "sample-code-flow-auto-login:build:production" + "browserTarget": "sample-code-flow-auto-login:build:production" }, "development": { - "buildTarget": "sample-code-flow-auto-login:build:development" + "browserTarget": "sample-code-flow-auto-login:build:development" } }, "defaultConfiguration": "development" @@ -231,7 +240,7 @@ "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { - "buildTarget": "sample-code-flow-auto-login:build" + "browserTarget": "sample-code-flow-auto-login:build" } }, "test": { @@ -241,7 +250,10 @@ "polyfills": "projects/sample-code-flow-auto-login/src/polyfills.ts", "tsConfig": "projects/sample-code-flow-auto-login/tsconfig.spec.json", "karmaConfig": "projects/sample-code-flow-auto-login/karma.conf.js", - "assets": ["projects/sample-code-flow-auto-login/src/favicon.ico", "projects/sample-code-flow-auto-login/src/assets"], + "assets": [ + "projects/sample-code-flow-auto-login/src/favicon.ico", + "projects/sample-code-flow-auto-login/src/assets" + ], "styles": ["projects/sample-code-flow-auto-login/src/styles.css"], "scripts": [] } @@ -249,7 +261,10 @@ "lint": { "builder": "@angular-eslint/builder:lint", "options": { - "lintFilePatterns": ["projects/sample-code-flow-auto-login/**/*.ts", "projects/sample-code-flow-auto-login/**/*.html"] + "lintFilePatterns": [ + "projects/sample-code-flow-auto-login/**/*.ts", + "projects/sample-code-flow-auto-login/**/*.html" + ] } } } @@ -322,14 +337,14 @@ "sslKey": "certs/dev_localhost.key", "sslCert": "certs/dev_localhost.pem", "port": 4201, - "buildTarget": "sample-code-flow-http-config:build" + "browserTarget": "sample-code-flow-http-config:build" }, "configurations": { "production": { - "buildTarget": "sample-code-flow-http-config:build:production" + "browserTarget": "sample-code-flow-http-config:build:production" }, "development": { - "buildTarget": "sample-code-flow-http-config:build:development" + "browserTarget": "sample-code-flow-http-config:build:development" } }, "defaultConfiguration": "development" @@ -337,7 +352,7 @@ "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { - "buildTarget": "sample-code-flow-http-config:build" + "browserTarget": "sample-code-flow-http-config:build" } }, "test": { @@ -347,7 +362,10 @@ "polyfills": "projects/sample-code-flow-http-config/src/polyfills.ts", "tsConfig": "projects/sample-code-flow-http-config/tsconfig.spec.json", "karmaConfig": "projects/sample-code-flow-http-config/karma.conf.js", - "assets": ["projects/sample-code-flow-http-config/src/favicon.ico", "projects/sample-code-flow-http-config/src/assets"], + "assets": [ + "projects/sample-code-flow-http-config/src/favicon.ico", + "projects/sample-code-flow-http-config/src/assets" + ], "styles": ["projects/sample-code-flow-http-config/src/styles.css"], "scripts": [] } @@ -355,7 +373,10 @@ "lint": { "builder": "@angular-eslint/builder:lint", "options": { - "lintFilePatterns": ["projects/sample-code-flow-http-config/**/*.ts", "projects/sample-code-flow-http-config/**/*.html"] + "lintFilePatterns": [ + "projects/sample-code-flow-http-config/**/*.ts", + "projects/sample-code-flow-http-config/**/*.html" + ] } } } @@ -376,7 +397,10 @@ "polyfills": "projects/sample-implicit-flow-google/src/polyfills.ts", "tsConfig": "projects/sample-implicit-flow-google/tsconfig.app.json", "aot": true, - "assets": ["projects/sample-implicit-flow-google/src/favicon.ico", "projects/sample-implicit-flow-google/src/assets"], + "assets": [ + "projects/sample-implicit-flow-google/src/favicon.ico", + "projects/sample-implicit-flow-google/src/assets" + ], "styles": ["projects/sample-implicit-flow-google/src/styles.css"], "scripts": [] }, @@ -424,14 +448,14 @@ "sslKey": "certs/dev_localhost.key", "sslCert": "certs/dev_localhost.pem", "port": 44386, - "buildTarget": "sample-implicit-flow-google:build" + "browserTarget": "sample-implicit-flow-google:build" }, "configurations": { "production": { - "buildTarget": "sample-implicit-flow-google:build:production" + "browserTarget": "sample-implicit-flow-google:build:production" }, "development": { - "buildTarget": "sample-implicit-flow-google:build:development" + "browserTarget": "sample-implicit-flow-google:build:development" } }, "defaultConfiguration": "development" @@ -439,7 +463,7 @@ "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { - "buildTarget": "sample-implicit-flow-google:build" + "browserTarget": "sample-implicit-flow-google:build" } }, "test": { @@ -449,7 +473,10 @@ "polyfills": "projects/sample-implicit-flow-google/src/polyfills.ts", "tsConfig": "projects/sample-implicit-flow-google/tsconfig.spec.json", "karmaConfig": "projects/sample-implicit-flow-google/karma.conf.js", - "assets": ["projects/sample-implicit-flow-google/src/favicon.ico", "projects/sample-implicit-flow-google/src/assets"], + "assets": [ + "projects/sample-implicit-flow-google/src/favicon.ico", + "projects/sample-implicit-flow-google/src/assets" + ], "styles": ["projects/sample-implicit-flow-google/src/styles.css"], "scripts": [] } @@ -457,7 +484,10 @@ "lint": { "builder": "@angular-eslint/builder:lint", "options": { - "lintFilePatterns": ["projects/sample-implicit-flow-google/**/*.ts", "projects/sample-implicit-flow-google/**/*.html"] + "lintFilePatterns": [ + "projects/sample-implicit-flow-google/**/*.ts", + "projects/sample-implicit-flow-google/**/*.html" + ] } } } @@ -530,14 +560,14 @@ "sslKey": "certs/dev_localhost.key", "sslCert": "certs/dev_localhost.pem", "port": 44347, - "buildTarget": "sample-code-flow-azuread:build" + "browserTarget": "sample-code-flow-azuread:build" }, "configurations": { "production": { - "buildTarget": "sample-code-flow-azuread:build:production" + "browserTarget": "sample-code-flow-azuread:build:production" }, "development": { - "buildTarget": "sample-code-flow-azuread:build:development" + "browserTarget": "sample-code-flow-azuread:build:development" } }, "defaultConfiguration": "development" @@ -545,7 +575,7 @@ "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { - "buildTarget": "sample-code-flow-azuread:build" + "browserTarget": "sample-code-flow-azuread:build" } }, "test": { @@ -567,7 +597,10 @@ "lint": { "builder": "@angular-eslint/builder:lint", "options": { - "lintFilePatterns": ["projects/sample-code-flow-azuread/**/*.ts", "projects/sample-code-flow-azuread/**/*.html"] + "lintFilePatterns": [ + "projects/sample-code-flow-azuread/**/*.ts", + "projects/sample-code-flow-azuread/**/*.html" + ] } } } @@ -640,14 +673,14 @@ "sslKey": "certs/dev_localhost.key", "sslCert": "certs/dev_localhost.pem", "port": 4200, - "buildTarget": "sample-code-flow-azure-b2c:build" + "browserTarget": "sample-code-flow-azure-b2c:build" }, "configurations": { "production": { - "buildTarget": "sample-code-flow-azure-b2c:build:production" + "browserTarget": "sample-code-flow-azure-b2c:build:production" }, "development": { - "buildTarget": "sample-code-flow-azure-b2c:build:development" + "browserTarget": "sample-code-flow-azure-b2c:build:development" } }, "defaultConfiguration": "development" @@ -655,7 +688,7 @@ "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { - "buildTarget": "sample-code-flow-azure-b2c:build" + "browserTarget": "sample-code-flow-azure-b2c:build" } }, "test": { @@ -665,7 +698,10 @@ "polyfills": "projects/sample-code-flow-azure-b2c/src/polyfills.ts", "tsConfig": "projects/sample-code-flow-azure-b2c/tsconfig.spec.json", "karmaConfig": "projects/sample-code-flow-azure-b2c/karma.conf.js", - "assets": ["projects/sample-code-flow-azure-b2c/src/favicon.ico", "projects/sample-code-flow-azure-b2c/src/assets"], + "assets": [ + "projects/sample-code-flow-azure-b2c/src/favicon.ico", + "projects/sample-code-flow-azure-b2c/src/assets" + ], "styles": ["projects/sample-code-flow-azure-b2c/src/styles.css"], "scripts": [] } @@ -673,7 +709,10 @@ "lint": { "builder": "@angular-eslint/builder:lint", "options": { - "lintFilePatterns": ["projects/sample-code-flow-azure-b2c/**/*.ts", "projects/sample-code-flow-azure-b2c/**/*.html"] + "lintFilePatterns": [ + "projects/sample-code-flow-azure-b2c/**/*.ts", + "projects/sample-code-flow-azure-b2c/**/*.html" + ] } } } @@ -699,7 +738,9 @@ "projects/sample-implicit-flow-silent-renew/src/assets", "projects/sample-implicit-flow-silent-renew/src/silent-renew.html" ], - "styles": ["projects/sample-implicit-flow-silent-renew/src/styles.css"], + "styles": [ + "projects/sample-implicit-flow-silent-renew/src/styles.css" + ], "scripts": [] }, "configurations": { @@ -746,14 +787,14 @@ "sslKey": "certs/dev_localhost.key", "sslCert": "certs/dev_localhost.pem", "port": 4202, - "buildTarget": "sample-implicit-flow-silent-renew:build" + "browserTarget": "sample-implicit-flow-silent-renew:build" }, "configurations": { "production": { - "buildTarget": "sample-implicit-flow-silent-renew:build:production" + "browserTarget": "sample-implicit-flow-silent-renew:build:production" }, "development": { - "buildTarget": "sample-implicit-flow-silent-renew:build:development" + "browserTarget": "sample-implicit-flow-silent-renew:build:development" } }, "defaultConfiguration": "development" @@ -761,7 +802,7 @@ "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { - "buildTarget": "sample-implicit-flow-silent-renew:build" + "browserTarget": "sample-implicit-flow-silent-renew:build" } }, "test": { @@ -775,7 +816,9 @@ "projects/sample-implicit-flow-silent-renew/src/favicon.ico", "projects/sample-implicit-flow-silent-renew/src/assets" ], - "styles": ["projects/sample-implicit-flow-silent-renew/src/styles.css"], + "styles": [ + "projects/sample-implicit-flow-silent-renew/src/styles.css" + ], "scripts": [] } }, @@ -806,7 +849,10 @@ "polyfills": "projects/sample-code-flow-auth0/src/polyfills.ts", "tsConfig": "projects/sample-code-flow-auth0/tsconfig.app.json", "aot": true, - "assets": ["projects/sample-code-flow-auth0/src/favicon.ico", "projects/sample-code-flow-auth0/src/assets"], + "assets": [ + "projects/sample-code-flow-auth0/src/favicon.ico", + "projects/sample-code-flow-auth0/src/assets" + ], "styles": ["projects/sample-code-flow-auth0/src/styles.css"], "scripts": [] }, @@ -854,14 +900,14 @@ "sslKey": "certs/dev_localhost.key", "sslCert": "certs/dev_localhost.pem", "port": 4210, - "buildTarget": "sample-code-flow-auth0:build" + "browserTarget": "sample-code-flow-auth0:build" }, "configurations": { "production": { - "buildTarget": "sample-code-flow-auth0:build:production" + "browserTarget": "sample-code-flow-auth0:build:production" }, "development": { - "buildTarget": "sample-code-flow-auth0:build:development" + "browserTarget": "sample-code-flow-auth0:build:development" } }, "defaultConfiguration": "development" @@ -869,7 +915,7 @@ "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { - "buildTarget": "sample-code-flow-auth0:build" + "browserTarget": "sample-code-flow-auth0:build" } }, "test": { @@ -879,7 +925,10 @@ "polyfills": "projects/sample-code-flow-auth0/src/polyfills.ts", "tsConfig": "projects/sample-code-flow-auth0/tsconfig.spec.json", "karmaConfig": "projects/sample-code-flow-auth0/karma.conf.js", - "assets": ["projects/sample-code-flow-auth0/src/favicon.ico", "projects/sample-code-flow-auth0/src/assets"], + "assets": [ + "projects/sample-code-flow-auth0/src/favicon.ico", + "projects/sample-code-flow-auth0/src/assets" + ], "styles": ["projects/sample-code-flow-auth0/src/styles.css"], "scripts": [] } @@ -887,7 +936,10 @@ "lint": { "builder": "@angular-eslint/builder:lint", "options": { - "lintFilePatterns": ["projects/sample-code-flow-auth0/**/*.ts", "projects/sample-code-flow-auth0/**/*.html"] + "lintFilePatterns": [ + "projects/sample-code-flow-auth0/**/*.ts", + "projects/sample-code-flow-auth0/**/*.html" + ] } } } @@ -908,8 +960,13 @@ "polyfills": "projects/sample-code-flow-refresh-tokens/src/polyfills.ts", "tsConfig": "projects/sample-code-flow-refresh-tokens/tsconfig.app.json", "aot": true, - "assets": ["projects/sample-code-flow-refresh-tokens/src/favicon.ico", "projects/sample-code-flow-refresh-tokens/src/assets"], - "styles": ["projects/sample-code-flow-refresh-tokens/src/styles.css"], + "assets": [ + "projects/sample-code-flow-refresh-tokens/src/favicon.ico", + "projects/sample-code-flow-refresh-tokens/src/assets" + ], + "styles": [ + "projects/sample-code-flow-refresh-tokens/src/styles.css" + ], "scripts": [] }, "configurations": { @@ -956,14 +1013,14 @@ "sslKey": "certs/dev_localhost.key", "sslCert": "certs/dev_localhost.pem", "port": 4204, - "buildTarget": "sample-code-flow-refresh-tokens:build" + "browserTarget": "sample-code-flow-refresh-tokens:build" }, "configurations": { "production": { - "buildTarget": "sample-code-flow-refresh-tokens:build:production" + "browserTarget": "sample-code-flow-refresh-tokens:build:production" }, "development": { - "buildTarget": "sample-code-flow-refresh-tokens:build:development" + "browserTarget": "sample-code-flow-refresh-tokens:build:development" } }, "defaultConfiguration": "development" @@ -971,7 +1028,7 @@ "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { - "buildTarget": "sample-code-flow-refresh-tokens:build" + "browserTarget": "sample-code-flow-refresh-tokens:build" } }, "test": { @@ -981,15 +1038,23 @@ "polyfills": "projects/sample-code-flow-refresh-tokens/src/polyfills.ts", "tsConfig": "projects/sample-code-flow-refresh-tokens/tsconfig.spec.json", "karmaConfig": "projects/sample-code-flow-refresh-tokens/karma.conf.js", - "assets": ["projects/sample-code-flow-refresh-tokens/src/favicon.ico", "projects/sample-code-flow-refresh-tokens/src/assets"], - "styles": ["projects/sample-code-flow-refresh-tokens/src/styles.css"], + "assets": [ + "projects/sample-code-flow-refresh-tokens/src/favicon.ico", + "projects/sample-code-flow-refresh-tokens/src/assets" + ], + "styles": [ + "projects/sample-code-flow-refresh-tokens/src/styles.css" + ], "scripts": [] } }, "lint": { "builder": "@angular-eslint/builder:lint", "options": { - "lintFilePatterns": ["projects/sample-code-flow-refresh-tokens/**/*.ts", "projects/sample-code-flow-refresh-tokens/**/*.html"] + "lintFilePatterns": [ + "projects/sample-code-flow-refresh-tokens/**/*.ts", + "projects/sample-code-flow-refresh-tokens/**/*.html" + ] } } } @@ -1057,14 +1122,14 @@ "sslKey": "certs/dev_localhost.key", "sslCert": "certs/dev_localhost.pem", "port": 4204, - "buildTarget": "sample-code-flow-standalone:build" + "browserTarget": "sample-code-flow-standalone:build" }, "configurations": { "production": { - "buildTarget": "sample-code-flow-standalone:build:production" + "browserTarget": "sample-code-flow-standalone:build:production" }, "development": { - "buildTarget": "sample-code-flow-standalone:build:development" + "browserTarget": "sample-code-flow-standalone:build:development" } }, "defaultConfiguration": "development" @@ -1072,7 +1137,7 @@ "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { - "buildTarget": "sample-code-flow-standalone:build" + "browserTarget": "sample-code-flow-standalone:build" } }, "test": { @@ -1082,7 +1147,10 @@ "polyfills": ["zone.js", "zone.js/testing"], "tsConfig": "projects/sample-code-flow-standalone/tsconfig.spec.json", "karmaConfig": "projects/sample-code-flow-standalone/karma.conf.js", - "assets": ["projects/sample-code-flow-standalone/src/favicon.ico", "projects/sample-code-flow-standalone/src/assets"], + "assets": [ + "projects/sample-code-flow-standalone/src/favicon.ico", + "projects/sample-code-flow-standalone/src/assets" + ], "styles": ["projects/sample-code-flow-standalone/src/styles.css"], "scripts": [] } @@ -1090,7 +1158,10 @@ "lint": { "builder": "@angular-eslint/builder:lint", "options": { - "lintFilePatterns": ["projects/sample-code-flow-standalone/**/*.ts", "projects/sample-code-flow-standalone/**/*.html"] + "lintFilePatterns": [ + "projects/sample-code-flow-standalone/**/*.ts", + "projects/sample-code-flow-standalone/**/*.html" + ] } } } @@ -1111,8 +1182,13 @@ "polyfills": "projects/sample-code-flow-multi-Azure-B2C/src/polyfills.ts", "tsConfig": "projects/sample-code-flow-multi-Azure-B2C/tsconfig.app.json", "aot": true, - "assets": ["projects/sample-code-flow-multi-Azure-B2C/src/favicon.ico", "projects/sample-code-flow-multi-Azure-B2C/src/assets"], - "styles": ["projects/sample-code-flow-multi-Azure-B2C/src/styles.css"], + "assets": [ + "projects/sample-code-flow-multi-Azure-B2C/src/favicon.ico", + "projects/sample-code-flow-multi-Azure-B2C/src/assets" + ], + "styles": [ + "projects/sample-code-flow-multi-Azure-B2C/src/styles.css" + ], "scripts": [] }, "configurations": { @@ -1159,14 +1235,14 @@ "sslKey": "certs/dev_localhost.key", "sslCert": "certs/dev_localhost.pem", "port": 4200, - "buildTarget": "sample-code-flow-multi-Azure-B2C:build" + "browserTarget": "sample-code-flow-multi-Azure-B2C:build" }, "configurations": { "production": { - "buildTarget": "sample-code-flow-multi-Azure-B2C:build:production" + "browserTarget": "sample-code-flow-multi-Azure-B2C:build:production" }, "development": { - "buildTarget": "sample-code-flow-multi-Azure-B2C:build:development" + "browserTarget": "sample-code-flow-multi-Azure-B2C:build:development" } }, "defaultConfiguration": "development" @@ -1174,7 +1250,7 @@ "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { - "buildTarget": "sample-code-flow-multi-Azure-B2C:build" + "browserTarget": "sample-code-flow-multi-Azure-B2C:build" } }, "test": { @@ -1184,15 +1260,23 @@ "polyfills": "projects/sample-code-flow-multi-Azure-B2C/src/polyfills.ts", "tsConfig": "projects/sample-code-flow-multi-Azure-B2C/tsconfig.spec.json", "karmaConfig": "projects/sample-code-flow-multi-Azure-B2C/karma.conf.js", - "assets": ["projects/sample-code-flow-multi-Azure-B2C/src/favicon.ico", "projects/sample-code-flow-multi-Azure-B2C/src/assets"], - "styles": ["projects/sample-code-flow-multi-Azure-B2C/src/styles.css"], + "assets": [ + "projects/sample-code-flow-multi-Azure-B2C/src/favicon.ico", + "projects/sample-code-flow-multi-Azure-B2C/src/assets" + ], + "styles": [ + "projects/sample-code-flow-multi-Azure-B2C/src/styles.css" + ], "scripts": [] } }, "lint": { "builder": "@angular-eslint/builder:lint", "options": { - "lintFilePatterns": ["projects/sample-code-flow-multi-Azure-B2C/**/*.ts", "projects/sample-code-flow-multi-Azure-B2C/**/*.html"] + "lintFilePatterns": [ + "projects/sample-code-flow-multi-Azure-B2C/**/*.ts", + "projects/sample-code-flow-multi-Azure-B2C/**/*.html" + ] } } } @@ -1213,7 +1297,10 @@ "polyfills": "projects/sample-code-flow-multi-AAD/src/polyfills.ts", "tsConfig": "projects/sample-code-flow-multi-AAD/tsconfig.app.json", "aot": true, - "assets": ["projects/sample-code-flow-multi-AAD/src/favicon.ico", "projects/sample-code-flow-multi-AAD/src/assets"], + "assets": [ + "projects/sample-code-flow-multi-AAD/src/favicon.ico", + "projects/sample-code-flow-multi-AAD/src/assets" + ], "styles": ["projects/sample-code-flow-multi-AAD/src/styles.css"], "scripts": [] }, @@ -1261,14 +1348,14 @@ "sslKey": "certs/dev_localhost.key", "sslCert": "certs/dev_localhost.pem", "port": 4200, - "buildTarget": "sample-code-flow-multi-AAD:build" + "browserTarget": "sample-code-flow-multi-AAD:build" }, "configurations": { "production": { - "buildTarget": "sample-code-flow-multi-AAD:build:production" + "browserTarget": "sample-code-flow-multi-AAD:build:production" }, "development": { - "buildTarget": "sample-code-flow-multi-AAD:build:development" + "browserTarget": "sample-code-flow-multi-AAD:build:development" } }, "defaultConfiguration": "development" @@ -1276,7 +1363,7 @@ "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { - "buildTarget": "sample-code-flow-multi-AAD:build" + "browserTarget": "sample-code-flow-multi-AAD:build" } }, "test": { @@ -1286,7 +1373,10 @@ "polyfills": "projects/sample-code-flow-multi-AAD/src/polyfills.ts", "tsConfig": "projects/sample-code-flow-multi-AAD/tsconfig.spec.json", "karmaConfig": "projects/sample-code-flow-multi-AAD/karma.conf.js", - "assets": ["projects/sample-code-flow-multi-AAD/src/favicon.ico", "projects/sample-code-flow-multi-AAD/src/assets"], + "assets": [ + "projects/sample-code-flow-multi-AAD/src/favicon.ico", + "projects/sample-code-flow-multi-AAD/src/assets" + ], "styles": ["projects/sample-code-flow-multi-AAD/src/styles.css"], "scripts": [] } @@ -1294,7 +1384,10 @@ "lint": { "builder": "@angular-eslint/builder:lint", "options": { - "lintFilePatterns": ["projects/sample-code-flow-multi-AAD/**/*.ts", "projects/sample-code-flow-multi-AAD/**/*.html"] + "lintFilePatterns": [ + "projects/sample-code-flow-multi-AAD/**/*.ts", + "projects/sample-code-flow-multi-AAD/**/*.html" + ] } } } @@ -1319,7 +1412,9 @@ "projects/sample-code-flow-multi-Auth0-ID4-popup/src/favicon.ico", "projects/sample-code-flow-multi-Auth0-ID4-popup/src/assets" ], - "styles": ["projects/sample-code-flow-multi-Auth0-ID4-popup/src/styles.css"], + "styles": [ + "projects/sample-code-flow-multi-Auth0-ID4-popup/src/styles.css" + ], "scripts": [] }, "configurations": { @@ -1366,14 +1461,14 @@ "sslKey": "certs/dev_localhost.key", "sslCert": "certs/dev_localhost.pem", "port": 4204, - "buildTarget": "sample-code-flow-multi-Auth0-ID4-popup:build" + "browserTarget": "sample-code-flow-multi-Auth0-ID4-popup:build" }, "configurations": { "production": { - "buildTarget": "sample-code-flow-multi-Auth0-ID4-popup:build:production" + "browserTarget": "sample-code-flow-multi-Auth0-ID4-popup:build:production" }, "development": { - "buildTarget": "sample-code-flow-multi-Auth0-ID4-popup:build:development" + "browserTarget": "sample-code-flow-multi-Auth0-ID4-popup:build:development" } }, "defaultConfiguration": "development" @@ -1381,7 +1476,7 @@ "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { - "buildTarget": "sample-code-flow-multi-Auth0-ID4-popup:build" + "browserTarget": "sample-code-flow-multi-Auth0-ID4-popup:build" } }, "test": { @@ -1395,7 +1490,9 @@ "projects/sample-code-flow-multi-Auth0-ID4-popup/src/favicon.ico", "projects/sample-code-flow-multi-Auth0-ID4-popup/src/assets" ], - "styles": ["projects/sample-code-flow-multi-Auth0-ID4-popup/src/styles.css"], + "styles": [ + "projects/sample-code-flow-multi-Auth0-ID4-popup/src/styles.css" + ], "scripts": [] } }, @@ -1426,8 +1523,13 @@ "polyfills": "projects/sample-code-flow-multi-Auth0-ID4/src/polyfills.ts", "tsConfig": "projects/sample-code-flow-multi-Auth0-ID4/tsconfig.app.json", "aot": true, - "assets": ["projects/sample-code-flow-multi-Auth0-ID4/src/favicon.ico", "projects/sample-code-flow-multi-Auth0-ID4/src/assets"], - "styles": ["projects/sample-code-flow-multi-Auth0-ID4/src/styles.css"], + "assets": [ + "projects/sample-code-flow-multi-Auth0-ID4/src/favicon.ico", + "projects/sample-code-flow-multi-Auth0-ID4/src/assets" + ], + "styles": [ + "projects/sample-code-flow-multi-Auth0-ID4/src/styles.css" + ], "scripts": [] }, "configurations": { @@ -1474,14 +1576,14 @@ "sslKey": "certs/dev_localhost.key", "sslCert": "certs/dev_localhost.pem", "port": 4204, - "buildTarget": "sample-code-flow-multi-Auth0-ID4:build" + "browserTarget": "sample-code-flow-multi-Auth0-ID4:build" }, "configurations": { "production": { - "buildTarget": "sample-code-flow-multi-Auth0-ID4:build:production" + "browserTarget": "sample-code-flow-multi-Auth0-ID4:build:production" }, "development": { - "buildTarget": "sample-code-flow-multi-Auth0-ID4:build:development" + "browserTarget": "sample-code-flow-multi-Auth0-ID4:build:development" } }, "defaultConfiguration": "development" @@ -1489,7 +1591,7 @@ "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { - "buildTarget": "sample-code-flow-multi-Auth0-ID4:build" + "browserTarget": "sample-code-flow-multi-Auth0-ID4:build" } }, "test": { @@ -1499,15 +1601,23 @@ "polyfills": "projects/sample-code-flow-multi-Auth0-ID4/src/polyfills.ts", "tsConfig": "projects/sample-code-flow-multi-Auth0-ID4/tsconfig.spec.json", "karmaConfig": "projects/sample-code-flow-multi-Auth0-ID4/karma.conf.js", - "assets": ["projects/sample-code-flow-multi-Auth0-ID4/src/favicon.ico", "projects/sample-code-flow-multi-Auth0-ID4/src/assets"], - "styles": ["projects/sample-code-flow-multi-Auth0-ID4/src/styles.css"], + "assets": [ + "projects/sample-code-flow-multi-Auth0-ID4/src/favicon.ico", + "projects/sample-code-flow-multi-Auth0-ID4/src/assets" + ], + "styles": [ + "projects/sample-code-flow-multi-Auth0-ID4/src/styles.css" + ], "scripts": [] } }, "lint": { "builder": "@angular-eslint/builder:lint", "options": { - "lintFilePatterns": ["projects/sample-code-flow-multi-Auth0-ID4/**/*.ts", "projects/sample-code-flow-multi-Auth0-ID4/**/*.html"] + "lintFilePatterns": [ + "projects/sample-code-flow-multi-Auth0-ID4/**/*.ts", + "projects/sample-code-flow-multi-Auth0-ID4/**/*.html" + ] } } } @@ -1528,7 +1638,10 @@ "polyfills": "projects/sample-code-flow-lazy-loaded/src/polyfills.ts", "tsConfig": "projects/sample-code-flow-lazy-loaded/tsconfig.app.json", "aot": true, - "assets": ["projects/sample-code-flow-lazy-loaded/src/favicon.ico", "projects/sample-code-flow-lazy-loaded/src/assets"], + "assets": [ + "projects/sample-code-flow-lazy-loaded/src/favicon.ico", + "projects/sample-code-flow-lazy-loaded/src/assets" + ], "styles": ["projects/sample-code-flow-lazy-loaded/src/styles.css"], "scripts": [] }, @@ -1575,14 +1688,14 @@ "options": { "sslKey": "certs/dev_localhost.key", "sslCert": "certs/dev_localhost.pem", - "buildTarget": "sample-code-flow-lazy-loaded:build" + "browserTarget": "sample-code-flow-lazy-loaded:build" }, "configurations": { "production": { - "buildTarget": "sample-code-flow-lazy-loaded:build:production" + "browserTarget": "sample-code-flow-lazy-loaded:build:production" }, "development": { - "buildTarget": "sample-code-flow-lazy-loaded:build:development" + "browserTarget": "sample-code-flow-lazy-loaded:build:development" } }, "defaultConfiguration": "development" @@ -1590,7 +1703,7 @@ "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { - "buildTarget": "sample-code-flow-lazy-loaded:build" + "browserTarget": "sample-code-flow-lazy-loaded:build" } }, "test": { @@ -1600,7 +1713,10 @@ "polyfills": "projects/sample-code-flow-lazy-loaded/src/polyfills.ts", "tsConfig": "projects/sample-code-flow-lazy-loaded/tsconfig.spec.json", "karmaConfig": "projects/sample-code-flow-lazy-loaded/karma.conf.js", - "assets": ["projects/sample-code-flow-lazy-loaded/src/favicon.ico", "projects/sample-code-flow-lazy-loaded/src/assets"], + "assets": [ + "projects/sample-code-flow-lazy-loaded/src/favicon.ico", + "projects/sample-code-flow-lazy-loaded/src/assets" + ], "styles": ["projects/sample-code-flow-lazy-loaded/src/styles.css"], "scripts": [] } @@ -1608,7 +1724,10 @@ "lint": { "builder": "@angular-eslint/builder:lint", "options": { - "lintFilePatterns": ["projects/sample-code-flow-lazy-loaded/**/*.ts", "projects/sample-code-flow-lazy-loaded/**/*.html"] + "lintFilePatterns": [ + "projects/sample-code-flow-lazy-loaded/**/*.ts", + "projects/sample-code-flow-lazy-loaded/**/*.html" + ] } } } @@ -1629,7 +1748,10 @@ "polyfills": "projects/sample-code-flow-popup/src/polyfills.ts", "tsConfig": "projects/sample-code-flow-popup/tsconfig.app.json", "aot": true, - "assets": ["projects/sample-code-flow-popup/src/favicon.ico", "projects/sample-code-flow-popup/src/assets"], + "assets": [ + "projects/sample-code-flow-popup/src/favicon.ico", + "projects/sample-code-flow-popup/src/assets" + ], "styles": ["projects/sample-code-flow-popup/src/styles.css"], "scripts": [] }, @@ -1677,14 +1799,14 @@ "sslKey": "certs/dev_localhost.key", "sslCert": "certs/dev_localhost.pem", "port": 4204, - "buildTarget": "sample-code-flow-popup:build" + "browserTarget": "sample-code-flow-popup:build" }, "configurations": { "production": { - "buildTarget": "sample-code-flow-popup:build:production" + "browserTarget": "sample-code-flow-popup:build:production" }, "development": { - "buildTarget": "sample-code-flow-popup:build:development" + "browserTarget": "sample-code-flow-popup:build:development" } }, "defaultConfiguration": "development" @@ -1692,7 +1814,7 @@ "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { - "buildTarget": "sample-code-flow-popup:build" + "browserTarget": "sample-code-flow-popup:build" } }, "test": { @@ -1702,7 +1824,10 @@ "polyfills": "projects/sample-code-flow-popup/src/polyfills.ts", "tsConfig": "projects/sample-code-flow-popup/tsconfig.spec.json", "karmaConfig": "projects/sample-code-flow-popup/karma.conf.js", - "assets": ["projects/sample-code-flow-popup/src/favicon.ico", "projects/sample-code-flow-popup/src/assets"], + "assets": [ + "projects/sample-code-flow-popup/src/favicon.ico", + "projects/sample-code-flow-popup/src/assets" + ], "styles": ["projects/sample-code-flow-popup/src/styles.css"], "scripts": [] } @@ -1777,14 +1902,14 @@ "sslKey": "certs/dev_localhost.key", "sslCert": "certs/dev_localhost.pem", "port": 4207, - "buildTarget": "sample-code-flow-par:build" + "browserTarget": "sample-code-flow-par:build" }, "configurations": { "production": { - "buildTarget": "sample-code-flow-par:build:production" + "browserTarget": "sample-code-flow-par:build:production" }, "development": { - "buildTarget": "sample-code-flow-par:build:development" + "browserTarget": "sample-code-flow-par:build:development" } }, "defaultConfiguration": "development" @@ -1792,7 +1917,7 @@ "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { - "buildTarget": "sample-code-flow-par:build" + "browserTarget": "sample-code-flow-par:build" } }, "test": { @@ -1802,7 +1927,10 @@ "polyfills": "projects/sample-code-flow-par/src/polyfills.ts", "tsConfig": "projects/sample-code-flow-par/tsconfig.spec.json", "karmaConfig": "projects/sample-code-flow-par/karma.conf.js", - "assets": ["projects/sample-code-flow-par/src/favicon.ico", "projects/sample-code-flow-par/src/assets"], + "assets": [ + "projects/sample-code-flow-par/src/favicon.ico", + "projects/sample-code-flow-par/src/assets" + ], "styles": ["projects/sample-code-flow-par/src/styles.css"], "scripts": [] } @@ -1833,7 +1961,9 @@ "projects/sample-code-flow-auto-login-all-routes/src/assets", "projects/sample-code-flow-auto-login-all-routes/src/silent-renew.html" ], - "styles": ["projects/sample-code-flow-auto-login-all-routes/src/styles.css"], + "styles": [ + "projects/sample-code-flow-auto-login-all-routes/src/styles.css" + ], "scripts": [] }, "configurations": { @@ -1875,14 +2005,14 @@ "sslKey": "certs/dev_localhost.key", "sslCert": "certs/dev_localhost.pem", "port": 4204, - "buildTarget": "sample-code-flow-auto-login-all-routes:build" + "browserTarget": "sample-code-flow-auto-login-all-routes:build" }, "configurations": { "production": { - "buildTarget": "sample-code-flow-auto-login-all-routes:build:production" + "browserTarget": "sample-code-flow-auto-login-all-routes:build:production" }, "development": { - "buildTarget": "sample-code-flow-auto-login-all-routes:build:development" + "browserTarget": "sample-code-flow-auto-login-all-routes:build:development" } }, "defaultConfiguration": "development" @@ -1890,7 +2020,7 @@ "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { - "buildTarget": "sample-code-flow-auto-login-all-routes:build" + "browserTarget": "sample-code-flow-auto-login-all-routes:build" } }, "test": { @@ -1904,7 +2034,9 @@ "projects/sample-code-flow-auto-login-all-routes/src/favicon.ico", "projects/sample-code-flow-auto-login-all-routes/src/assets" ], - "styles": ["projects/sample-code-flow-auto-login-all-routes/src/styles.css"], + "styles": [ + "projects/sample-code-flow-auto-login-all-routes/src/styles.css" + ], "scripts": [] } } diff --git a/projects/sample-code-flow-auth0/src/app/home/home.component.ts b/projects/sample-code-flow-auth0/src/app/home/home.component.ts index 67cb6ab1..db3773f4 100644 --- a/projects/sample-code-flow-auth0/src/app/home/home.component.ts +++ b/projects/sample-code-flow-auth0/src/app/home/home.component.ts @@ -1,28 +1,18 @@ import { Component, OnInit } from '@angular/core'; -import { - OidcClientNotification, - OidcSecurityService, - OpenIdConfiguration, - UserDataResult, -} from 'angular-auth-oidc-client'; -import { Observable } from 'rxjs'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-home', templateUrl: 'home.component.html', }) export class HomeComponent implements OnInit { - configuration$: Observable; - userDataChanged$: Observable>; - userData$: Observable; + configuration$ = this.oidcSecurityService.getConfiguration(); + userData$ = this.oidcSecurityService.userData$; isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} ngOnInit() { - this.configuration$ = this.oidcSecurityService.getConfiguration(); - this.userData$ = this.oidcSecurityService.userData$; - this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; diff --git a/projects/sample-code-flow-refresh-tokens/src/app/home/home.component.ts b/projects/sample-code-flow-refresh-tokens/src/app/home/home.component.ts index e56e9c29..4579d6f7 100644 --- a/projects/sample-code-flow-refresh-tokens/src/app/home/home.component.ts +++ b/projects/sample-code-flow-refresh-tokens/src/app/home/home.component.ts @@ -1,27 +1,17 @@ import { Component, OnInit } from '@angular/core'; -import { - OidcClientNotification, - OidcSecurityService, - OpenIdConfiguration, - UserDataResult, -} from 'angular-auth-oidc-client'; -import { Observable } from 'rxjs'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-home', templateUrl: 'home.component.html', }) export class HomeComponent implements OnInit { - configuration$: Observable; - userDataChanged$: Observable>; - userData$: Observable; + configuration$ = this.oidcSecurityService.getConfiguration(); + userData$ = this.oidcSecurityService.userData$; isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} ngOnInit() { - this.configuration$ = this.oidcSecurityService.getConfiguration(); - this.userData$ = this.oidcSecurityService.userData$; - this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; From 6a9bc547cdfabc12f6f0d4a7eff3d1df32397858 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Mon, 18 Mar 2024 10:10:04 +0100 Subject: [PATCH 38/56] Refactor authentication code in home and navigation components --- .../src/app/home/home.component.ts | 6 ++---- .../src/app/navigation/navigation.component.ts | 2 +- .../src/app/unauthorized/unauthorized.component.ts | 2 +- .../src/app/home/home.component.ts | 6 ++---- .../src/app/nav-menu/nav-menu.component.ts | 2 +- 5 files changed, 7 insertions(+), 11 deletions(-) diff --git a/projects/sample-code-flow-auto-login-all-routes/src/app/home/home.component.ts b/projects/sample-code-flow-auto-login-all-routes/src/app/home/home.component.ts index 041acd88..44f8933b 100644 --- a/projects/sample-code-flow-auto-login-all-routes/src/app/home/home.component.ts +++ b/projects/sample-code-flow-auto-login-all-routes/src/app/home/home.component.ts @@ -1,13 +1,12 @@ import { Component, OnInit } from '@angular/core'; -import { OidcSecurityService, UserDataResult } from 'angular-auth-oidc-client'; -import { Observable } from 'rxjs'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-home', templateUrl: 'home.component.html', }) export class HomeComponent implements OnInit { - userData$: Observable; + userData$ = this.oidcSecurityService.userData$; isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} @@ -20,6 +19,5 @@ export class HomeComponent implements OnInit { console.warn('authenticated: ', isAuthenticated); } ); - this.userData$ = this.oidcSecurityService.userData$; } } diff --git a/projects/sample-code-flow-auto-login-all-routes/src/app/navigation/navigation.component.ts b/projects/sample-code-flow-auto-login-all-routes/src/app/navigation/navigation.component.ts index b072893d..cba9bcb8 100644 --- a/projects/sample-code-flow-auto-login-all-routes/src/app/navigation/navigation.component.ts +++ b/projects/sample-code-flow-auto-login-all-routes/src/app/navigation/navigation.component.ts @@ -7,7 +7,7 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; styleUrls: ['navigation.component.css'], }) export class NavigationComponent implements OnInit { - isAuthenticated: boolean; + isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} diff --git a/projects/sample-code-flow-auto-login-all-routes/src/app/unauthorized/unauthorized.component.ts b/projects/sample-code-flow-auto-login-all-routes/src/app/unauthorized/unauthorized.component.ts index 834791f2..c8e06462 100644 --- a/projects/sample-code-flow-auto-login-all-routes/src/app/unauthorized/unauthorized.component.ts +++ b/projects/sample-code-flow-auto-login-all-routes/src/app/unauthorized/unauthorized.component.ts @@ -6,7 +6,7 @@ import { Component, OnInit } from '@angular/core'; }) export class UnauthorizedComponent implements OnInit { public message: string; - public values: any[]; + public values: any[] = []; constructor() { this.message = 'UnauthorizedComponent constructor'; diff --git a/projects/sample-code-flow-azure-b2c/src/app/home/home.component.ts b/projects/sample-code-flow-azure-b2c/src/app/home/home.component.ts index 041acd88..44f8933b 100644 --- a/projects/sample-code-flow-azure-b2c/src/app/home/home.component.ts +++ b/projects/sample-code-flow-azure-b2c/src/app/home/home.component.ts @@ -1,13 +1,12 @@ import { Component, OnInit } from '@angular/core'; -import { OidcSecurityService, UserDataResult } from 'angular-auth-oidc-client'; -import { Observable } from 'rxjs'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-home', templateUrl: 'home.component.html', }) export class HomeComponent implements OnInit { - userData$: Observable; + userData$ = this.oidcSecurityService.userData$; isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} @@ -20,6 +19,5 @@ export class HomeComponent implements OnInit { console.warn('authenticated: ', isAuthenticated); } ); - this.userData$ = this.oidcSecurityService.userData$; } } diff --git a/projects/sample-code-flow-azure-b2c/src/app/nav-menu/nav-menu.component.ts b/projects/sample-code-flow-azure-b2c/src/app/nav-menu/nav-menu.component.ts index c0486cbe..834f980d 100644 --- a/projects/sample-code-flow-azure-b2c/src/app/nav-menu/nav-menu.component.ts +++ b/projects/sample-code-flow-azure-b2c/src/app/nav-menu/nav-menu.component.ts @@ -8,7 +8,7 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; }) export class NavMenuComponent implements OnInit { isExpanded = false; - isAuthenticated: boolean; + isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} From 1bf7ea61a6a99c36ed8f3ea8fbbd1b7ac9219d56 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Mon, 18 Mar 2024 10:14:04 +0100 Subject: [PATCH 39/56] Refactor authentication code in home and navigation components --- .../src/app/home/home.component.ts | 7 ++-- .../app/navigation/navigation.component.ts | 2 +- .../unauthorized/unauthorized.component.ts | 2 +- .../src/app/home/home.component.ts | 20 +++-------- .../src/app/home/home.component.ts | 34 ++++--------------- 5 files changed, 15 insertions(+), 50 deletions(-) diff --git a/projects/sample-code-flow-auto-login/src/app/home/home.component.ts b/projects/sample-code-flow-auto-login/src/app/home/home.component.ts index 6b5d9cb0..44f8933b 100644 --- a/projects/sample-code-flow-auto-login/src/app/home/home.component.ts +++ b/projects/sample-code-flow-auto-login/src/app/home/home.component.ts @@ -1,13 +1,12 @@ import { Component, OnInit } from '@angular/core'; -import { OidcSecurityService, UserDataResult } from 'angular-auth-oidc-client'; -import { Observable } from 'rxjs'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-home', templateUrl: 'home.component.html', }) export class HomeComponent implements OnInit { - userData$: Observable; + userData$ = this.oidcSecurityService.userData$; isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} @@ -20,7 +19,5 @@ export class HomeComponent implements OnInit { console.warn('authenticated: ', isAuthenticated); } ); - - this.userData$ = this.oidcSecurityService.userData$; } } diff --git a/projects/sample-code-flow-auto-login/src/app/navigation/navigation.component.ts b/projects/sample-code-flow-auto-login/src/app/navigation/navigation.component.ts index b072893d..cba9bcb8 100644 --- a/projects/sample-code-flow-auto-login/src/app/navigation/navigation.component.ts +++ b/projects/sample-code-flow-auto-login/src/app/navigation/navigation.component.ts @@ -7,7 +7,7 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; styleUrls: ['navigation.component.css'], }) export class NavigationComponent implements OnInit { - isAuthenticated: boolean; + isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} diff --git a/projects/sample-code-flow-auto-login/src/app/unauthorized/unauthorized.component.ts b/projects/sample-code-flow-auto-login/src/app/unauthorized/unauthorized.component.ts index 834791f2..c8e06462 100644 --- a/projects/sample-code-flow-auto-login/src/app/unauthorized/unauthorized.component.ts +++ b/projects/sample-code-flow-auto-login/src/app/unauthorized/unauthorized.component.ts @@ -6,7 +6,7 @@ import { Component, OnInit } from '@angular/core'; }) export class UnauthorizedComponent implements OnInit { public message: string; - public values: any[]; + public values: any[] = []; constructor() { this.message = 'UnauthorizedComponent constructor'; diff --git a/projects/sample-code-flow-http-config/src/app/home/home.component.ts b/projects/sample-code-flow-http-config/src/app/home/home.component.ts index e2d9e753..3a6ce9cb 100644 --- a/projects/sample-code-flow-http-config/src/app/home/home.component.ts +++ b/projects/sample-code-flow-http-config/src/app/home/home.component.ts @@ -1,31 +1,19 @@ import { Component, OnInit } from '@angular/core'; -import { - OidcClientNotification, - OidcSecurityService, - OpenIdConfiguration, - UserDataResult, -} from 'angular-auth-oidc-client'; -import { Observable } from 'rxjs'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-home', templateUrl: 'home.component.html', }) export class HomeComponent implements OnInit { - configuration$: Observable; - userDataChanged$: Observable>; - userData$: Observable; + configuration$ = this.oidcSecurityService.getConfiguration(); + userData$ = this.oidcSecurityService.userData$; isAuthenticated = false; - checkSessionChanged$: Observable; - checkSessionChanged: any; + checkSessionChanged$ = this.oidcSecurityService.checkSessionChanged$; constructor(public oidcSecurityService: OidcSecurityService) {} ngOnInit() { - this.configuration$ = this.oidcSecurityService.getConfiguration(); - this.userData$ = this.oidcSecurityService.userData$; - this.checkSessionChanged$ = this.oidcSecurityService.checkSessionChanged$; - this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; diff --git a/projects/sample-code-flow-multi-iframe/src/app/home/home.component.ts b/projects/sample-code-flow-multi-iframe/src/app/home/home.component.ts index 1df2c263..575de6bf 100644 --- a/projects/sample-code-flow-multi-iframe/src/app/home/home.component.ts +++ b/projects/sample-code-flow-multi-iframe/src/app/home/home.component.ts @@ -1,32 +1,20 @@ import { Component, OnInit } from '@angular/core'; -import { - AuthenticatedResult, - OidcClientNotification, - OidcSecurityService, - OpenIdConfiguration, - UserDataResult, -} from 'angular-auth-oidc-client'; -import { Observable } from 'rxjs'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-home', templateUrl: 'home.component.html', }) export class HomeComponent implements OnInit { - configurations: OpenIdConfiguration[]; - userDataChanged$: Observable>; - userData$: Observable; - isAuthenticated$: Observable; + configurations = this.oidcSecurityService.getConfigurations(); + userData$ = this.oidcSecurityService.userData$; + isAuthenticated$ = this.oidcSecurityService.isAuthenticated$; constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { - this.configurations = this.oidcSecurityService.getConfigurations(); - this.userData$ = this.oidcSecurityService.userData$; - this.isAuthenticated$ = this.oidcSecurityService.isAuthenticated$; - } + ngOnInit() {} - login(configId: string) { + login(configId: string | undefined) { this.oidcSecurityService.authorize(configId); } @@ -36,15 +24,7 @@ export class HomeComponent implements OnInit { .subscribe((result) => console.warn(result)); } - logout(configId: string) { + logout(configId: string | undefined) { this.oidcSecurityService.logoff(configId); } - - // login(configId: string) { - // this.oidcSecurityService.authorize(configId); - // } - - // logout(configId: string) { - // this.oidcSecurityService.logoff(configId); - // } } From 0f1e04b0423684992412534b9c669e40df4b6b58 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Mon, 18 Mar 2024 11:15:21 +0100 Subject: [PATCH 40/56] Update template bindings in multiple components --- .../unauthorized/unauthorized.component.ts | 8 ++----- .../src/app/customers/customers.component.ts | 8 ++----- .../src/app/protected/protected.component.ts | 8 ++----- .../unauthorized/unauthorized.component.ts | 13 ++---------- .../src/app/customers/customers.component.ts | 8 ++----- .../src/app/protected/protected.component.ts | 8 ++----- .../unauthorized/unauthorized.component.ts | 13 ++---------- .../src/app/forbidden/forbidden.component.ts | 8 ++----- .../src/app/protected/protected.component.ts | 8 ++----- .../unauthorized/unauthorized.component.ts | 8 ++----- .../src/app/forbidden/forbidden.component.ts | 8 ++----- .../src/app/home/home.component.ts | 6 ++---- .../src/app/nav-menu/nav-menu.component.ts | 2 +- .../src/app/protected/protected.component.ts | 8 ++----- .../unauthorized/unauthorized.component.ts | 8 ++----- .../src/app/home/home.component.html | 2 +- .../unauthorized/unauthorized.component.ts | 8 ++----- .../src/app/lazy/lazy.module.ts | 4 +--- .../unauthorized/unauthorized.component.ts | 8 ++----- .../unauthorized/unauthorized.component.ts | 8 ++----- .../unauthorized/unauthorized.component.ts | 8 ++----- .../unauthorized/unauthorized.component.ts | 8 ++----- .../unauthorized/unauthorized.component.ts | 8 ++----- .../unauthorized/unauthorized.component.ts | 8 ++----- .../unauthorized/unauthorized.component.ts | 8 ++----- .../src/app/customers/customers.component.ts | 8 ++----- .../src/app/protected/protected.component.ts | 8 ++----- .../unauthorized/unauthorized.component.ts | 13 ++---------- .../app/auto-login/auto-login.component.ts | 2 -- .../src/app/forbidden/forbidden.component.ts | 13 ++---------- .../src/app/home/home.component.ts | 6 ++---- .../unauthorized/unauthorized.component.ts | 13 ++---------- .../src/app/home/home.component.html | 2 +- .../src/app/home/home.component.ts | 21 +++++-------------- .../unauthorized/unauthorized.component.ts | 8 ++----- 35 files changed, 67 insertions(+), 219 deletions(-) diff --git a/projects/sample-code-flow-auth0/src/app/unauthorized/unauthorized.component.ts b/projects/sample-code-flow-auth0/src/app/unauthorized/unauthorized.component.ts index dbe96504..0ab5a6c4 100644 --- a/projects/sample-code-flow-auth0/src/app/unauthorized/unauthorized.component.ts +++ b/projects/sample-code-flow-auth0/src/app/unauthorized/unauthorized.component.ts @@ -1,11 +1,7 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-unauthorized', templateUrl: 'unauthorized.component.html', }) -export class UnauthorizedComponent implements OnInit { - constructor() {} - - ngOnInit() {} -} +export class UnauthorizedComponent {} diff --git a/projects/sample-code-flow-auto-login-all-routes/src/app/customers/customers.component.ts b/projects/sample-code-flow-auto-login-all-routes/src/app/customers/customers.component.ts index 7833b920..553e924d 100644 --- a/projects/sample-code-flow-auto-login-all-routes/src/app/customers/customers.component.ts +++ b/projects/sample-code-flow-auto-login-all-routes/src/app/customers/customers.component.ts @@ -1,12 +1,8 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-customers', templateUrl: './customers.component.html', styleUrls: ['./customers.component.css'], }) -export class CustomersComponent implements OnInit { - constructor() {} - - ngOnInit() {} -} +export class CustomersComponent {} diff --git a/projects/sample-code-flow-auto-login-all-routes/src/app/protected/protected.component.ts b/projects/sample-code-flow-auto-login-all-routes/src/app/protected/protected.component.ts index 02476990..cf8dec94 100644 --- a/projects/sample-code-flow-auto-login-all-routes/src/app/protected/protected.component.ts +++ b/projects/sample-code-flow-auto-login-all-routes/src/app/protected/protected.component.ts @@ -1,12 +1,8 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-protected', templateUrl: './protected.component.html', styleUrls: ['./protected.component.css'], }) -export class ProtectedComponent implements OnInit { - constructor() {} - - ngOnInit() {} -} +export class ProtectedComponent {} diff --git a/projects/sample-code-flow-auto-login-all-routes/src/app/unauthorized/unauthorized.component.ts b/projects/sample-code-flow-auto-login-all-routes/src/app/unauthorized/unauthorized.component.ts index c8e06462..0ab5a6c4 100644 --- a/projects/sample-code-flow-auto-login-all-routes/src/app/unauthorized/unauthorized.component.ts +++ b/projects/sample-code-flow-auto-login-all-routes/src/app/unauthorized/unauthorized.component.ts @@ -1,16 +1,7 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-unauthorized', templateUrl: 'unauthorized.component.html', }) -export class UnauthorizedComponent implements OnInit { - public message: string; - public values: any[] = []; - - constructor() { - this.message = 'UnauthorizedComponent constructor'; - } - - ngOnInit() {} -} +export class UnauthorizedComponent {} diff --git a/projects/sample-code-flow-auto-login/src/app/customers/customers.component.ts b/projects/sample-code-flow-auto-login/src/app/customers/customers.component.ts index 18ca1ef1..553e924d 100644 --- a/projects/sample-code-flow-auto-login/src/app/customers/customers.component.ts +++ b/projects/sample-code-flow-auto-login/src/app/customers/customers.component.ts @@ -1,12 +1,8 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-customers', templateUrl: './customers.component.html', styleUrls: ['./customers.component.css'], }) -export class CustomersComponent implements OnInit { - constructor() {} - - ngOnInit(): void {} -} +export class CustomersComponent {} diff --git a/projects/sample-code-flow-auto-login/src/app/protected/protected.component.ts b/projects/sample-code-flow-auto-login/src/app/protected/protected.component.ts index 02476990..cf8dec94 100644 --- a/projects/sample-code-flow-auto-login/src/app/protected/protected.component.ts +++ b/projects/sample-code-flow-auto-login/src/app/protected/protected.component.ts @@ -1,12 +1,8 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-protected', templateUrl: './protected.component.html', styleUrls: ['./protected.component.css'], }) -export class ProtectedComponent implements OnInit { - constructor() {} - - ngOnInit() {} -} +export class ProtectedComponent {} diff --git a/projects/sample-code-flow-auto-login/src/app/unauthorized/unauthorized.component.ts b/projects/sample-code-flow-auto-login/src/app/unauthorized/unauthorized.component.ts index c8e06462..0ab5a6c4 100644 --- a/projects/sample-code-flow-auto-login/src/app/unauthorized/unauthorized.component.ts +++ b/projects/sample-code-flow-auto-login/src/app/unauthorized/unauthorized.component.ts @@ -1,16 +1,7 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-unauthorized', templateUrl: 'unauthorized.component.html', }) -export class UnauthorizedComponent implements OnInit { - public message: string; - public values: any[] = []; - - constructor() { - this.message = 'UnauthorizedComponent constructor'; - } - - ngOnInit() {} -} +export class UnauthorizedComponent {} diff --git a/projects/sample-code-flow-azure-b2c/src/app/forbidden/forbidden.component.ts b/projects/sample-code-flow-azure-b2c/src/app/forbidden/forbidden.component.ts index b5416954..df59c551 100644 --- a/projects/sample-code-flow-azure-b2c/src/app/forbidden/forbidden.component.ts +++ b/projects/sample-code-flow-azure-b2c/src/app/forbidden/forbidden.component.ts @@ -1,12 +1,8 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-forbidden', templateUrl: './forbidden.component.html', styleUrls: ['./forbidden.component.css'], }) -export class ForbiddenComponent implements OnInit { - constructor() {} - - ngOnInit() {} -} +export class ForbiddenComponent {} diff --git a/projects/sample-code-flow-azure-b2c/src/app/protected/protected.component.ts b/projects/sample-code-flow-azure-b2c/src/app/protected/protected.component.ts index 02476990..cf8dec94 100644 --- a/projects/sample-code-flow-azure-b2c/src/app/protected/protected.component.ts +++ b/projects/sample-code-flow-azure-b2c/src/app/protected/protected.component.ts @@ -1,12 +1,8 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-protected', templateUrl: './protected.component.html', styleUrls: ['./protected.component.css'], }) -export class ProtectedComponent implements OnInit { - constructor() {} - - ngOnInit() {} -} +export class ProtectedComponent {} diff --git a/projects/sample-code-flow-azure-b2c/src/app/unauthorized/unauthorized.component.ts b/projects/sample-code-flow-azure-b2c/src/app/unauthorized/unauthorized.component.ts index fe06a691..c5c1482b 100644 --- a/projects/sample-code-flow-azure-b2c/src/app/unauthorized/unauthorized.component.ts +++ b/projects/sample-code-flow-azure-b2c/src/app/unauthorized/unauthorized.component.ts @@ -1,12 +1,8 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-unauthorized', templateUrl: './unauthorized.component.html', styleUrls: ['./unauthorized.component.css'], }) -export class UnauthorizedComponent implements OnInit { - constructor() {} - - ngOnInit() {} -} +export class UnauthorizedComponent {} diff --git a/projects/sample-code-flow-azuread/src/app/forbidden/forbidden.component.ts b/projects/sample-code-flow-azuread/src/app/forbidden/forbidden.component.ts index b5416954..df59c551 100644 --- a/projects/sample-code-flow-azuread/src/app/forbidden/forbidden.component.ts +++ b/projects/sample-code-flow-azuread/src/app/forbidden/forbidden.component.ts @@ -1,12 +1,8 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-forbidden', templateUrl: './forbidden.component.html', styleUrls: ['./forbidden.component.css'], }) -export class ForbiddenComponent implements OnInit { - constructor() {} - - ngOnInit() {} -} +export class ForbiddenComponent {} diff --git a/projects/sample-code-flow-azuread/src/app/home/home.component.ts b/projects/sample-code-flow-azuread/src/app/home/home.component.ts index 041acd88..44f8933b 100644 --- a/projects/sample-code-flow-azuread/src/app/home/home.component.ts +++ b/projects/sample-code-flow-azuread/src/app/home/home.component.ts @@ -1,13 +1,12 @@ import { Component, OnInit } from '@angular/core'; -import { OidcSecurityService, UserDataResult } from 'angular-auth-oidc-client'; -import { Observable } from 'rxjs'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-home', templateUrl: 'home.component.html', }) export class HomeComponent implements OnInit { - userData$: Observable; + userData$ = this.oidcSecurityService.userData$; isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} @@ -20,6 +19,5 @@ export class HomeComponent implements OnInit { console.warn('authenticated: ', isAuthenticated); } ); - this.userData$ = this.oidcSecurityService.userData$; } } diff --git a/projects/sample-code-flow-azuread/src/app/nav-menu/nav-menu.component.ts b/projects/sample-code-flow-azuread/src/app/nav-menu/nav-menu.component.ts index e1b120bc..6b9881f0 100644 --- a/projects/sample-code-flow-azuread/src/app/nav-menu/nav-menu.component.ts +++ b/projects/sample-code-flow-azuread/src/app/nav-menu/nav-menu.component.ts @@ -9,7 +9,7 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; export class NavMenuComponent implements OnInit { isExpanded = false; - isAuthenticated: boolean; + isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} diff --git a/projects/sample-code-flow-azuread/src/app/protected/protected.component.ts b/projects/sample-code-flow-azuread/src/app/protected/protected.component.ts index 02476990..cf8dec94 100644 --- a/projects/sample-code-flow-azuread/src/app/protected/protected.component.ts +++ b/projects/sample-code-flow-azuread/src/app/protected/protected.component.ts @@ -1,12 +1,8 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-protected', templateUrl: './protected.component.html', styleUrls: ['./protected.component.css'], }) -export class ProtectedComponent implements OnInit { - constructor() {} - - ngOnInit() {} -} +export class ProtectedComponent {} diff --git a/projects/sample-code-flow-azuread/src/app/unauthorized/unauthorized.component.ts b/projects/sample-code-flow-azuread/src/app/unauthorized/unauthorized.component.ts index fe06a691..c5c1482b 100644 --- a/projects/sample-code-flow-azuread/src/app/unauthorized/unauthorized.component.ts +++ b/projects/sample-code-flow-azuread/src/app/unauthorized/unauthorized.component.ts @@ -1,12 +1,8 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-unauthorized', templateUrl: './unauthorized.component.html', styleUrls: ['./unauthorized.component.css'], }) -export class UnauthorizedComponent implements OnInit { - constructor() {} - - ngOnInit() {} -} +export class UnauthorizedComponent {} diff --git a/projects/sample-code-flow-http-config/src/app/home/home.component.html b/projects/sample-code-flow-http-config/src/app/home/home.component.html index 9699438c..05257e97 100644 --- a/projects/sample-code-flow-http-config/src/app/home/home.component.html +++ b/projects/sample-code-flow-http-config/src/app/home/home.component.html @@ -17,7 +17,7 @@
userData
{{ userData$ | async | json }}
- {{ checkSessionChanged }} + {{ checkSessionChanged$ | async }}
diff --git a/projects/sample-code-flow-http-config/src/app/unauthorized/unauthorized.component.ts b/projects/sample-code-flow-http-config/src/app/unauthorized/unauthorized.component.ts index dbe96504..0ab5a6c4 100644 --- a/projects/sample-code-flow-http-config/src/app/unauthorized/unauthorized.component.ts +++ b/projects/sample-code-flow-http-config/src/app/unauthorized/unauthorized.component.ts @@ -1,11 +1,7 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-unauthorized', templateUrl: 'unauthorized.component.html', }) -export class UnauthorizedComponent implements OnInit { - constructor() {} - - ngOnInit() {} -} +export class UnauthorizedComponent {} diff --git a/projects/sample-code-flow-lazy-loaded/src/app/lazy/lazy.module.ts b/projects/sample-code-flow-lazy-loaded/src/app/lazy/lazy.module.ts index e6b8a70d..36e12980 100644 --- a/projects/sample-code-flow-lazy-loaded/src/app/lazy/lazy.module.ts +++ b/projects/sample-code-flow-lazy-loaded/src/app/lazy/lazy.module.ts @@ -7,6 +7,4 @@ import { LazyComponent } from './lazy.component'; declarations: [LazyComponent], imports: [CommonModule, LazyRoutingModule], }) -export class LazyModule { - constructor() {} -} +export class LazyModule {} diff --git a/projects/sample-code-flow-multi-AAD/src/app/unauthorized/unauthorized.component.ts b/projects/sample-code-flow-multi-AAD/src/app/unauthorized/unauthorized.component.ts index dbe96504..0ab5a6c4 100644 --- a/projects/sample-code-flow-multi-AAD/src/app/unauthorized/unauthorized.component.ts +++ b/projects/sample-code-flow-multi-AAD/src/app/unauthorized/unauthorized.component.ts @@ -1,11 +1,7 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-unauthorized', templateUrl: 'unauthorized.component.html', }) -export class UnauthorizedComponent implements OnInit { - constructor() {} - - ngOnInit() {} -} +export class UnauthorizedComponent {} diff --git a/projects/sample-code-flow-multi-Auth0-ID4-popup/src/app/unauthorized/unauthorized.component.ts b/projects/sample-code-flow-multi-Auth0-ID4-popup/src/app/unauthorized/unauthorized.component.ts index dbe96504..0ab5a6c4 100644 --- a/projects/sample-code-flow-multi-Auth0-ID4-popup/src/app/unauthorized/unauthorized.component.ts +++ b/projects/sample-code-flow-multi-Auth0-ID4-popup/src/app/unauthorized/unauthorized.component.ts @@ -1,11 +1,7 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-unauthorized', templateUrl: 'unauthorized.component.html', }) -export class UnauthorizedComponent implements OnInit { - constructor() {} - - ngOnInit() {} -} +export class UnauthorizedComponent {} diff --git a/projects/sample-code-flow-multi-Auth0-ID4/src/app/unauthorized/unauthorized.component.ts b/projects/sample-code-flow-multi-Auth0-ID4/src/app/unauthorized/unauthorized.component.ts index dbe96504..0ab5a6c4 100644 --- a/projects/sample-code-flow-multi-Auth0-ID4/src/app/unauthorized/unauthorized.component.ts +++ b/projects/sample-code-flow-multi-Auth0-ID4/src/app/unauthorized/unauthorized.component.ts @@ -1,11 +1,7 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-unauthorized', templateUrl: 'unauthorized.component.html', }) -export class UnauthorizedComponent implements OnInit { - constructor() {} - - ngOnInit() {} -} +export class UnauthorizedComponent {} diff --git a/projects/sample-code-flow-multi-Azure-B2C/src/app/unauthorized/unauthorized.component.ts b/projects/sample-code-flow-multi-Azure-B2C/src/app/unauthorized/unauthorized.component.ts index dbe96504..0ab5a6c4 100644 --- a/projects/sample-code-flow-multi-Azure-B2C/src/app/unauthorized/unauthorized.component.ts +++ b/projects/sample-code-flow-multi-Azure-B2C/src/app/unauthorized/unauthorized.component.ts @@ -1,11 +1,7 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-unauthorized', templateUrl: 'unauthorized.component.html', }) -export class UnauthorizedComponent implements OnInit { - constructor() {} - - ngOnInit() {} -} +export class UnauthorizedComponent {} diff --git a/projects/sample-code-flow-multi-iframe/src/app/unauthorized/unauthorized.component.ts b/projects/sample-code-flow-multi-iframe/src/app/unauthorized/unauthorized.component.ts index dbe96504..0ab5a6c4 100644 --- a/projects/sample-code-flow-multi-iframe/src/app/unauthorized/unauthorized.component.ts +++ b/projects/sample-code-flow-multi-iframe/src/app/unauthorized/unauthorized.component.ts @@ -1,11 +1,7 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-unauthorized', templateUrl: 'unauthorized.component.html', }) -export class UnauthorizedComponent implements OnInit { - constructor() {} - - ngOnInit() {} -} +export class UnauthorizedComponent {} diff --git a/projects/sample-code-flow-par/src/app/unauthorized/unauthorized.component.ts b/projects/sample-code-flow-par/src/app/unauthorized/unauthorized.component.ts index dbe96504..0ab5a6c4 100644 --- a/projects/sample-code-flow-par/src/app/unauthorized/unauthorized.component.ts +++ b/projects/sample-code-flow-par/src/app/unauthorized/unauthorized.component.ts @@ -1,11 +1,7 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-unauthorized', templateUrl: 'unauthorized.component.html', }) -export class UnauthorizedComponent implements OnInit { - constructor() {} - - ngOnInit() {} -} +export class UnauthorizedComponent {} diff --git a/projects/sample-code-flow-refresh-tokens/src/app/unauthorized/unauthorized.component.ts b/projects/sample-code-flow-refresh-tokens/src/app/unauthorized/unauthorized.component.ts index dbe96504..0ab5a6c4 100644 --- a/projects/sample-code-flow-refresh-tokens/src/app/unauthorized/unauthorized.component.ts +++ b/projects/sample-code-flow-refresh-tokens/src/app/unauthorized/unauthorized.component.ts @@ -1,11 +1,7 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-unauthorized', templateUrl: 'unauthorized.component.html', }) -export class UnauthorizedComponent implements OnInit { - constructor() {} - - ngOnInit() {} -} +export class UnauthorizedComponent {} diff --git a/projects/sample-code-flow-standalone/src/app/customers/customers.component.ts b/projects/sample-code-flow-standalone/src/app/customers/customers.component.ts index 582b9ec0..e0b5217e 100644 --- a/projects/sample-code-flow-standalone/src/app/customers/customers.component.ts +++ b/projects/sample-code-flow-standalone/src/app/customers/customers.component.ts @@ -1,4 +1,4 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-customers', @@ -6,8 +6,4 @@ import { Component, OnInit } from '@angular/core'; styleUrls: ['./customers.component.css'], standalone: true, }) -export class CustomersComponent implements OnInit { - constructor() {} - - ngOnInit(): void {} -} +export class CustomersComponent {} diff --git a/projects/sample-code-flow-standalone/src/app/protected/protected.component.ts b/projects/sample-code-flow-standalone/src/app/protected/protected.component.ts index 4accef62..720e0ca0 100644 --- a/projects/sample-code-flow-standalone/src/app/protected/protected.component.ts +++ b/projects/sample-code-flow-standalone/src/app/protected/protected.component.ts @@ -1,4 +1,4 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-protected', @@ -6,8 +6,4 @@ import { Component, OnInit } from '@angular/core'; styleUrls: ['./protected.component.css'], standalone: true, }) -export class ProtectedComponent implements OnInit { - constructor() {} - - ngOnInit() {} -} +export class ProtectedComponent {} diff --git a/projects/sample-code-flow-standalone/src/app/unauthorized/unauthorized.component.ts b/projects/sample-code-flow-standalone/src/app/unauthorized/unauthorized.component.ts index 66c0ab6c..c1bdf954 100644 --- a/projects/sample-code-flow-standalone/src/app/unauthorized/unauthorized.component.ts +++ b/projects/sample-code-flow-standalone/src/app/unauthorized/unauthorized.component.ts @@ -1,17 +1,8 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-unauthorized', templateUrl: 'unauthorized.component.html', standalone: true, }) -export class UnauthorizedComponent implements OnInit { - public message: string; - public values: any[]; - - constructor() { - this.message = 'UnauthorizedComponent constructor'; - } - - ngOnInit() {} -} +export class UnauthorizedComponent {} diff --git a/projects/sample-implicit-flow-google/src/app/auto-login/auto-login.component.ts b/projects/sample-implicit-flow-google/src/app/auto-login/auto-login.component.ts index d63c1bfb..ad692e5b 100644 --- a/projects/sample-implicit-flow-google/src/app/auto-login/auto-login.component.ts +++ b/projects/sample-implicit-flow-google/src/app/auto-login/auto-login.component.ts @@ -6,8 +6,6 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; templateUrl: './auto-login.component.html', }) export class AutoLoginComponent implements OnInit { - lang: any; - constructor(public oidcSecurityService: OidcSecurityService) {} ngOnInit() { diff --git a/projects/sample-implicit-flow-google/src/app/forbidden/forbidden.component.ts b/projects/sample-implicit-flow-google/src/app/forbidden/forbidden.component.ts index 7431c8b3..1d58d56d 100644 --- a/projects/sample-implicit-flow-google/src/app/forbidden/forbidden.component.ts +++ b/projects/sample-implicit-flow-google/src/app/forbidden/forbidden.component.ts @@ -1,16 +1,7 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-forbidden', templateUrl: 'forbidden.component.html', }) -export class ForbiddenComponent implements OnInit { - public message: string; - public values: any[]; - - constructor() { - this.message = 'ForbiddenComponent constructor'; - } - - ngOnInit() {} -} +export class ForbiddenComponent {} diff --git a/projects/sample-implicit-flow-google/src/app/home/home.component.ts b/projects/sample-implicit-flow-google/src/app/home/home.component.ts index 041acd88..44f8933b 100644 --- a/projects/sample-implicit-flow-google/src/app/home/home.component.ts +++ b/projects/sample-implicit-flow-google/src/app/home/home.component.ts @@ -1,13 +1,12 @@ import { Component, OnInit } from '@angular/core'; -import { OidcSecurityService, UserDataResult } from 'angular-auth-oidc-client'; -import { Observable } from 'rxjs'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-home', templateUrl: 'home.component.html', }) export class HomeComponent implements OnInit { - userData$: Observable; + userData$ = this.oidcSecurityService.userData$; isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} @@ -20,6 +19,5 @@ export class HomeComponent implements OnInit { console.warn('authenticated: ', isAuthenticated); } ); - this.userData$ = this.oidcSecurityService.userData$; } } diff --git a/projects/sample-implicit-flow-google/src/app/unauthorized/unauthorized.component.ts b/projects/sample-implicit-flow-google/src/app/unauthorized/unauthorized.component.ts index 834791f2..0ab5a6c4 100644 --- a/projects/sample-implicit-flow-google/src/app/unauthorized/unauthorized.component.ts +++ b/projects/sample-implicit-flow-google/src/app/unauthorized/unauthorized.component.ts @@ -1,16 +1,7 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-unauthorized', templateUrl: 'unauthorized.component.html', }) -export class UnauthorizedComponent implements OnInit { - public message: string; - public values: any[]; - - constructor() { - this.message = 'UnauthorizedComponent constructor'; - } - - ngOnInit() {} -} +export class UnauthorizedComponent {} diff --git a/projects/sample-implicit-flow-silent-renew/src/app/home/home.component.html b/projects/sample-implicit-flow-silent-renew/src/app/home/home.component.html index 98d4bf83..fccd2ae4 100644 --- a/projects/sample-implicit-flow-silent-renew/src/app/home/home.component.html +++ b/projects/sample-implicit-flow-silent-renew/src/app/home/home.component.html @@ -16,7 +16,7 @@
userData
{{ userData$ | async | json }}
- {{ checkSessionChanged }} + {{ checkSessionChanged$ | async }}
diff --git a/projects/sample-implicit-flow-silent-renew/src/app/home/home.component.ts b/projects/sample-implicit-flow-silent-renew/src/app/home/home.component.ts index 3a19f043..f636ee13 100644 --- a/projects/sample-implicit-flow-silent-renew/src/app/home/home.component.ts +++ b/projects/sample-implicit-flow-silent-renew/src/app/home/home.component.ts @@ -1,30 +1,19 @@ import { Component, OnInit } from '@angular/core'; -import { - OidcClientNotification, - OidcSecurityService, - OpenIdConfiguration, - UserDataResult, -} from 'angular-auth-oidc-client'; -import { Observable } from 'rxjs'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-home', templateUrl: 'home.component.html', }) export class HomeComponent implements OnInit { - configuration$: Observable; - userDataChanged$: Observable>; - userData$: Observable; + configuration$ = this.oidcSecurityService.getConfiguration(); + userData$ = this.oidcSecurityService.userData$; isAuthenticated = false; - checkSessionChanged$: Observable; - checkSessionChanged: any; + checkSessionChanged$ = this.oidcSecurityService.checkSessionChanged$; constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { - this.configuration$ = this.oidcSecurityService.getConfiguration(); - this.userData$ = this.oidcSecurityService.userData$; - this.checkSessionChanged$ = this.oidcSecurityService.checkSessionChanged$; + ngOnInit() { this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; diff --git a/projects/sample-implicit-flow-silent-renew/src/app/unauthorized/unauthorized.component.ts b/projects/sample-implicit-flow-silent-renew/src/app/unauthorized/unauthorized.component.ts index dbe96504..0ab5a6c4 100644 --- a/projects/sample-implicit-flow-silent-renew/src/app/unauthorized/unauthorized.component.ts +++ b/projects/sample-implicit-flow-silent-renew/src/app/unauthorized/unauthorized.component.ts @@ -1,11 +1,7 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'app-unauthorized', templateUrl: 'unauthorized.component.html', }) -export class UnauthorizedComponent implements OnInit { - constructor() {} - - ngOnInit() {} -} +export class UnauthorizedComponent {} From 549676e864f83f5181eec73db26a7fc8298ec94b Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Mon, 18 Mar 2024 11:18:44 +0100 Subject: [PATCH 41/56] Refactor authentication code in HomeComponent and NavigationComponent --- .../src/app/home/home.component.ts | 34 ++++++------------- .../src/app/home/home.component.ts | 9 ++--- .../app/navigation/navigation.component.ts | 6 ++-- 3 files changed, 16 insertions(+), 33 deletions(-) diff --git a/projects/sample-code-flow-multi-Azure-B2C/src/app/home/home.component.ts b/projects/sample-code-flow-multi-Azure-B2C/src/app/home/home.component.ts index 6e36843a..3539e329 100644 --- a/projects/sample-code-flow-multi-Azure-B2C/src/app/home/home.component.ts +++ b/projects/sample-code-flow-multi-Azure-B2C/src/app/home/home.component.ts @@ -1,32 +1,18 @@ -import { Component, OnInit } from '@angular/core'; -import { - AuthenticatedResult, - OidcClientNotification, - OidcSecurityService, - OpenIdConfiguration, - UserDataResult, -} from 'angular-auth-oidc-client'; -import { Observable } from 'rxjs'; +import { Component } from '@angular/core'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-home', templateUrl: 'home.component.html', }) -export class HomeComponent implements OnInit { - configurations: OpenIdConfiguration[]; - userDataChanged$: Observable>; - userData$: Observable; - isAuthenticated$: Observable; +export class HomeComponent { + configurations = this.oidcSecurityService.getConfigurations(); + userData$ = this.oidcSecurityService.userData$; + isAuthenticated$ = this.oidcSecurityService.isAuthenticated$; constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { - this.configurations = this.oidcSecurityService.getConfigurations(); - this.userData$ = this.oidcSecurityService.userData$; - this.isAuthenticated$ = this.oidcSecurityService.isAuthenticated$; - } - - login(configId: string) { + login(configId: string | undefined) { this.oidcSecurityService.authorize(configId); } @@ -36,13 +22,13 @@ export class HomeComponent implements OnInit { .subscribe((result) => console.warn(result)); } - logout(configId: string) { + logout(configId: string | undefined) { this.oidcSecurityService.logoff(configId); } - refreshSession(configId: string) { + refreshSession(configId: string | undefined) { this.oidcSecurityService - .forceRefreshSession(null, configId) + .forceRefreshSession(undefined, configId) .subscribe((result) => console.log(result)); } } diff --git a/projects/sample-code-flow-standalone/src/app/home/home.component.ts b/projects/sample-code-flow-standalone/src/app/home/home.component.ts index 3778641a..06ee5539 100644 --- a/projects/sample-code-flow-standalone/src/app/home/home.component.ts +++ b/projects/sample-code-flow-standalone/src/app/home/home.component.ts @@ -1,7 +1,6 @@ -import { Component, OnInit } from '@angular/core'; -import { OidcSecurityService, UserDataResult } from 'angular-auth-oidc-client'; -import { Observable } from 'rxjs'; import { AsyncPipe, JsonPipe } from '@angular/common'; +import { Component, OnInit } from '@angular/core'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-home', @@ -10,7 +9,7 @@ import { AsyncPipe, JsonPipe } from '@angular/common'; imports: [AsyncPipe, JsonPipe], }) export class HomeComponent implements OnInit { - userData$: Observable; + userData$ = this.oidcSecurityService.userData$; isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} @@ -23,7 +22,5 @@ export class HomeComponent implements OnInit { console.warn('authenticated: ', isAuthenticated); } ); - - this.userData$ = this.oidcSecurityService.userData$; } } diff --git a/projects/sample-code-flow-standalone/src/app/navigation/navigation.component.ts b/projects/sample-code-flow-standalone/src/app/navigation/navigation.component.ts index 87400fc2..f1dd5621 100644 --- a/projects/sample-code-flow-standalone/src/app/navigation/navigation.component.ts +++ b/projects/sample-code-flow-standalone/src/app/navigation/navigation.component.ts @@ -1,7 +1,7 @@ +import { NgIf } from '@angular/common'; import { Component, OnInit } from '@angular/core'; -import { OidcSecurityService } from 'angular-auth-oidc-client'; import { RouterLink } from '@angular/router'; -import { NgIf } from '@angular/common'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-navigation', @@ -11,7 +11,7 @@ import { NgIf } from '@angular/common'; imports: [RouterLink, NgIf], }) export class NavigationComponent implements OnInit { - isAuthenticated: boolean; + isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} From 89af4870e5d5b915f21c3a7b20a0c46a96c73fe7 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Mon, 18 Mar 2024 11:30:43 +0100 Subject: [PATCH 42/56] Refactor Angular component imports and remove unused lifecycle hooks --- .../src/app/app.component.ts | 8 +--- .../src/app/home/home.component.ts | 37 +++++----------- .../src/app/home/home.component.ts | 43 ++++++------------- .../src/app/home/home.component.ts | 41 ++++++------------ .../src/app/home/home.component.ts | 6 +-- .../src/app/home/home.component.ts | 17 ++------ .../src/app/app.component.ts | 16 ++----- 7 files changed, 48 insertions(+), 120 deletions(-) diff --git a/projects/sample-code-flow-azuread/src/app/app.component.ts b/projects/sample-code-flow-azuread/src/app/app.component.ts index a46fd01f..ec6ee442 100644 --- a/projects/sample-code-flow-azuread/src/app/app.component.ts +++ b/projects/sample-code-flow-azuread/src/app/app.component.ts @@ -1,17 +1,13 @@ -import { Component, OnDestroy, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-root', templateUrl: 'app.component.html', }) -export class AppComponent implements OnInit, OnDestroy { +export class AppComponent { constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() {} - - ngOnDestroy(): void {} - login() { console.log('start login'); this.oidcSecurityService.authorize(); diff --git a/projects/sample-code-flow-multi-AAD/src/app/home/home.component.ts b/projects/sample-code-flow-multi-AAD/src/app/home/home.component.ts index 587af52c..2221d2eb 100644 --- a/projects/sample-code-flow-multi-AAD/src/app/home/home.component.ts +++ b/projects/sample-code-flow-multi-AAD/src/app/home/home.component.ts @@ -1,35 +1,18 @@ -import { Component, OnInit } from '@angular/core'; -import { - AuthenticatedResult, - OidcClientNotification, - OidcSecurityService, - OpenIdConfiguration, - UserDataResult, -} from 'angular-auth-oidc-client'; -import { Observable } from 'rxjs'; +import { Component } from '@angular/core'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-home', templateUrl: 'home.component.html', }) -export class HomeComponent implements OnInit { - configurations: OpenIdConfiguration[]; - - userDataChanged$: Observable>; - - userData$: Observable; - - isAuthenticated$: Observable; +export class HomeComponent { + configurations = this.oidcSecurityService.getConfigurations(); + userData$ = this.oidcSecurityService.userData$; + isAuthenticated$ = this.oidcSecurityService.isAuthenticated$; constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { - this.configurations = this.oidcSecurityService.getConfigurations(); - this.userData$ = this.oidcSecurityService.userData$; - this.isAuthenticated$ = this.oidcSecurityService.isAuthenticated$; - } - - login(configId: string) { + login(configId: string | undefined) { this.oidcSecurityService.authorize(configId); } @@ -39,15 +22,15 @@ export class HomeComponent implements OnInit { .subscribe((result) => console.warn(result)); } - logout(configId: string) { + logout(configId: string | undefined) { this.oidcSecurityService .logoff(configId) .subscribe((result) => console.log(result)); } - refreshSession(configId: string) { + refreshSession(configId: string | undefined) { this.oidcSecurityService - .forceRefreshSession(null, configId) + .forceRefreshSession(undefined, configId) .subscribe((result) => console.log(result)); } } diff --git a/projects/sample-code-flow-multi-Auth0-ID4-popup/src/app/home/home.component.ts b/projects/sample-code-flow-multi-Auth0-ID4-popup/src/app/home/home.component.ts index ba96ae4f..eb9f372e 100644 --- a/projects/sample-code-flow-multi-Auth0-ID4-popup/src/app/home/home.component.ts +++ b/projects/sample-code-flow-multi-Auth0-ID4-popup/src/app/home/home.component.ts @@ -1,41 +1,26 @@ -import { Component, OnInit } from '@angular/core'; -import { - AuthenticatedResult, - OidcClientNotification, - OidcSecurityService, - OpenIdConfiguration, - UserDataResult, -} from 'angular-auth-oidc-client'; -import { Observable } from 'rxjs'; +import { Component } from '@angular/core'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-home', templateUrl: 'home.component.html', }) -export class HomeComponent implements OnInit { - configurations: OpenIdConfiguration[]; +export class HomeComponent { + configurations = this.oidcSecurityService.getConfigurations(); - userDataChanged$: Observable>; + userData$ = this.oidcSecurityService.userData$; - userData$: Observable; - - isAuthenticated$: Observable; + isAuthenticated$ = this.oidcSecurityService.isAuthenticated$; constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { - this.configurations = this.oidcSecurityService.getConfigurations(); - this.userData$ = this.oidcSecurityService.userData$; - this.isAuthenticated$ = this.oidcSecurityService.isAuthenticated$; - } - login(configId: string) { this.oidcSecurityService.authorize(configId); } - loginWithPopup(configId: string) { + loginWithPopup(configId: string | undefined) { this.oidcSecurityService - .authorizeWithPopUp(null, null, configId) + .authorizeWithPopUp(undefined, undefined, configId) .subscribe(({ isAuthenticated, userData, accessToken, errorMessage }) => { console.log(isAuthenticated); console.log(userData); @@ -54,19 +39,19 @@ export class HomeComponent implements OnInit { .subscribe((result) => console.warn(result)); } - logout(configId: string) { + logout(configId: string | undefined) { this.oidcSecurityService .logoff(configId) .subscribe((result) => console.log(result)); } - refreshSessionId4(configId: string) { + refreshSessionId4(configId: string | undefined) { this.oidcSecurityService - .forceRefreshSession(null, configId) + .forceRefreshSession(undefined, configId) .subscribe((result) => console.log(result)); } - refreshSessionAuth0(configId: string) { + refreshSessionAuth0(configId: string | undefined) { this.oidcSecurityService .forceRefreshSession( { scope: 'openid profile offline_access auth0-user-api-spa' }, @@ -75,13 +60,13 @@ export class HomeComponent implements OnInit { .subscribe((result) => console.log(result)); } - logoffAndRevokeTokens(configId: string) { + logoffAndRevokeTokens(configId: string | undefined) { this.oidcSecurityService .logoffAndRevokeTokens(configId) .subscribe((result) => console.log(result)); } - revokeRefreshToken(configId: string) { + revokeRefreshToken(configId: string | undefined) { this.oidcSecurityService .revokeRefreshToken(null, configId) .subscribe((result) => console.log(result)); diff --git a/projects/sample-code-flow-multi-Auth0-ID4/src/app/home/home.component.ts b/projects/sample-code-flow-multi-Auth0-ID4/src/app/home/home.component.ts index 317638a8..4a00c5e2 100644 --- a/projects/sample-code-flow-multi-Auth0-ID4/src/app/home/home.component.ts +++ b/projects/sample-code-flow-multi-Auth0-ID4/src/app/home/home.component.ts @@ -1,35 +1,20 @@ -import { Component, OnInit } from '@angular/core'; -import { - AuthenticatedResult, - OidcClientNotification, - OidcSecurityService, - OpenIdConfiguration, - UserDataResult, -} from 'angular-auth-oidc-client'; -import { Observable } from 'rxjs'; +import { Component } from '@angular/core'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-home', templateUrl: 'home.component.html', }) -export class HomeComponent implements OnInit { - configurations: OpenIdConfiguration[]; +export class HomeComponent { + configurations = this.oidcSecurityService.getConfigurations(); - userDataChanged$: Observable>; + userData$ = this.oidcSecurityService.userData$; - userData$: Observable; - - isAuthenticated$: Observable; + isAuthenticated$ = this.oidcSecurityService.isAuthenticated$; constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { - this.configurations = this.oidcSecurityService.getConfigurations(); - this.userData$ = this.oidcSecurityService.userData$; - this.isAuthenticated$ = this.oidcSecurityService.isAuthenticated$; - } - - login(configId: string) { + login(configId: string | undefined) { this.oidcSecurityService.authorize(configId); } @@ -39,19 +24,19 @@ export class HomeComponent implements OnInit { .subscribe((result) => console.warn(result)); } - logout(configId: string) { + logout(configId: string | undefined) { this.oidcSecurityService .logoff(configId) .subscribe((result) => console.log(result)); } - refreshSessionId4(configId: string) { + refreshSessionId4(configId: string | undefined) { this.oidcSecurityService - .forceRefreshSession(null, configId) + .forceRefreshSession(undefined, configId) .subscribe((result) => console.log(result)); } - refreshSessionAuth0(configId: string) { + refreshSessionAuth0(configId: string | undefined) { this.oidcSecurityService .forceRefreshSession( { scope: 'openid profile offline_access auth0-user-api-spa' }, @@ -60,13 +45,13 @@ export class HomeComponent implements OnInit { .subscribe((result) => console.log(result)); } - logoffAndRevokeTokens(configId: string) { + logoffAndRevokeTokens(configId: string | undefined) { this.oidcSecurityService .logoffAndRevokeTokens(configId) .subscribe((result) => console.log(result)); } - revokeRefreshToken(configId: string) { + revokeRefreshToken(configId: string | undefined) { this.oidcSecurityService .revokeRefreshToken(null, configId) .subscribe((result) => console.log(result)); diff --git a/projects/sample-code-flow-multi-iframe/src/app/home/home.component.ts b/projects/sample-code-flow-multi-iframe/src/app/home/home.component.ts index 575de6bf..d5658451 100644 --- a/projects/sample-code-flow-multi-iframe/src/app/home/home.component.ts +++ b/projects/sample-code-flow-multi-iframe/src/app/home/home.component.ts @@ -1,19 +1,17 @@ -import { Component, OnInit } from '@angular/core'; +import { Component } from '@angular/core'; import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-home', templateUrl: 'home.component.html', }) -export class HomeComponent implements OnInit { +export class HomeComponent { configurations = this.oidcSecurityService.getConfigurations(); userData$ = this.oidcSecurityService.userData$; isAuthenticated$ = this.oidcSecurityService.isAuthenticated$; constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() {} - login(configId: string | undefined) { this.oidcSecurityService.authorize(configId); } diff --git a/projects/sample-code-flow-par/src/app/home/home.component.ts b/projects/sample-code-flow-par/src/app/home/home.component.ts index 9f57ad25..3beced07 100644 --- a/projects/sample-code-flow-par/src/app/home/home.component.ts +++ b/projects/sample-code-flow-par/src/app/home/home.component.ts @@ -1,27 +1,18 @@ import { Component, OnInit } from '@angular/core'; -import { - OidcClientNotification, - OidcSecurityService, - OpenIdConfiguration, - UserDataResult, -} from 'angular-auth-oidc-client'; -import { Observable } from 'rxjs'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-home', templateUrl: 'home.component.html', }) export class HomeComponent implements OnInit { - configuration$: Observable; - userDataChanged$: Observable>; - userData$: Observable; + configuration$ = this.oidcSecurityService.getConfiguration(); + userData$ = this.oidcSecurityService.userData$; isAuthenticated = false; + constructor(public oidcSecurityService: OidcSecurityService) {} ngOnInit() { - this.configuration$ = this.oidcSecurityService.getConfiguration(); - this.userData$ = this.oidcSecurityService.userData$; - this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; diff --git a/projects/sample-code-flow-popup/src/app/app.component.ts b/projects/sample-code-flow-popup/src/app/app.component.ts index bdeb01ae..e1f60be2 100644 --- a/projects/sample-code-flow-popup/src/app/app.component.ts +++ b/projects/sample-code-flow-popup/src/app/app.component.ts @@ -1,10 +1,5 @@ import { Component } from '@angular/core'; -import { - OidcSecurityService, - OpenIdConfiguration, - UserDataResult, -} from 'angular-auth-oidc-client'; -import { Observable } from 'rxjs'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-root', @@ -12,20 +7,15 @@ import { Observable } from 'rxjs'; styleUrls: ['./app.component.css'], }) export class AppComponent { - title = 'sample-code-flow-popup'; + userData$ = this.oidcSecurityService.userData$; - userData$: Observable; - - configuration$: Observable; + configuration$ = this.oidcSecurityService.getConfiguration(); isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} ngOnInit() { - this.configuration$ = this.oidcSecurityService.getConfiguration(); - this.userData$ = this.oidcSecurityService.userData$; - this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; From b02b89351b22d80d8da937ee1068ef9782f80e89 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Mon, 18 Mar 2024 11:47:59 +0100 Subject: [PATCH 43/56] Fix ngOnInit method signature in app components --- .eslintrc.json | 15 ++++++++++++--- .../angular-auth-oidc-client/.eslintrc.json | 11 ----------- .../src/app/app.component.spec.ts | 4 ++++ .../src/app/app.component.ts | 2 +- .../src/app/home/home.component.ts | 16 +++++++++------- .../src/app/app.component.spec.ts | 4 ++++ .../src/app/app.component.ts | 2 +- .../src/app/forbidden/forbidden.component.ts | 2 +- .../src/app/home/home.component.ts | 1 + .../src/app/home/home.component.ts | 3 ++- .../src/app/nav-menu/nav-menu.component.ts | 13 +++++++------ .../src/app/app.component.ts | 6 +++--- .../src/app/home/home.component.ts | 3 ++- .../src/app/nav-menu/nav-menu.component.ts | 13 +++++++------ .../src/app/app.component.spec.ts | 4 ++++ .../src/app/app.component.ts | 2 +- .../src/app/auth-config.module.ts | 3 +-- .../src/app/home/home.component.ts | 13 ++++++++----- .../src/app/app.component.spec.ts | 4 ++++ .../src/app/app.component.ts | 2 +- .../src/app/lazy/lazy.component.ts | 5 +++-- .../src/app/app.component.spec.ts | 4 ++++ .../src/app/app.component.ts | 2 +- .../src/app/home/home.component.ts | 10 ++++++---- .../src/app/app.component.spec.ts | 4 ++++ .../src/app/app.component.ts | 2 +- .../src/app/home/home.component.ts | 18 +++++++++--------- .../src/app/app.component.spec.ts | 4 ++++ .../src/app/app.component.ts | 3 +-- .../src/app/home/home.component.ts | 14 +++++++------- .../src/app/app.component.spec.ts | 4 ++++ .../src/app/app.component.ts | 2 +- .../src/app/home/home.component.ts | 10 ++++++---- .../src/app/app.component.spec.ts | 4 ++++ .../src/app/home/home.component.ts | 2 ++ .../src/app/app.component.spec.ts | 4 ++++ .../src/app/app.component.ts | 4 ++-- .../src/app/home/home.component.ts | 17 ++++++++++------- .../src/app/app.component.spec.ts | 4 ++++ .../src/app/app.component.ts | 14 +++++++------- .../src/app/forbidden/forbidden.component.ts | 4 ++-- .../src/app/home/home.component.ts | 3 ++- .../app/navigation/navigation.component.ts | 8 ++++---- .../src/app/app.component.spec.ts | 4 ++++ .../src/app/app.component.ts | 19 +++++++++---------- .../app/auto-login/auto-login.component.ts | 2 +- .../src/app/home/home.component.ts | 3 ++- .../app/navigation/navigation.component.ts | 8 ++++---- .../src/app/app.component.spec.ts | 4 ++++ .../src/app/app.component.ts | 2 +- .../src/app/home/home.component.ts | 14 +++++++++----- 51 files changed, 199 insertions(+), 126 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index c4a8de71..a4d8e5d7 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -21,7 +21,6 @@ "format": ["PascalCase"] } ], - "newline-before-return": "error", "max-len": "off", "no-useless-constructor": "off", "lines-between-class-members": ["error", "always"], @@ -36,12 +35,22 @@ "no-empty": ["error"], "@typescript-eslint/no-empty-function": ["error"], "no-unused-vars": "off", - "@typescript-eslint/no-unused-vars": ["error"], "@typescript-eslint/ban-types": ["error"], "no-useless-escape": ["error"], "no-prototype-builtins": ["error"], "prefer-spread": ["error"], - "@typescript-eslint/no-explicit-any": "off" + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/typedef": ["error"], + "@typescript-eslint/explicit-function-return-type": ["error"], + "newline-before-return": ["error"], + "@typescript-eslint/no-unused-vars": [ + "error", + { + "argsIgnorePattern": "^_", + "varsIgnorePattern": "^_", + "caughtErrorsIgnorePattern": "^_" + } + ] } }, { diff --git a/projects/angular-auth-oidc-client/.eslintrc.json b/projects/angular-auth-oidc-client/.eslintrc.json index bace0286..c39ff084 100644 --- a/projects/angular-auth-oidc-client/.eslintrc.json +++ b/projects/angular-auth-oidc-client/.eslintrc.json @@ -28,17 +28,6 @@ "style": "camelCase" } ], - "@typescript-eslint/typedef": ["error"], - "@typescript-eslint/explicit-function-return-type": ["error"], - "newline-before-return": ["error"], - "@typescript-eslint/no-unused-vars": [ - "error", - { - "argsIgnorePattern": "^_", - "varsIgnorePattern": "^_", - "caughtErrorsIgnorePattern": "^_" - } - ], "no-restricted-imports": [ "error", { diff --git a/projects/sample-code-flow-auth0/src/app/app.component.spec.ts b/projects/sample-code-flow-auth0/src/app/app.component.spec.ts index ca37aa2b..7627c677 100644 --- a/projects/sample-code-flow-auth0/src/app/app.component.spec.ts +++ b/projects/sample-code-flow-auth0/src/app/app.component.spec.ts @@ -11,19 +11,23 @@ describe('AppComponent', () => { it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app).toBeTruthy(); }); it(`should have as title 'testSts'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app.title).toEqual('testSts'); }); it('should render title in a h1 tag', () => { const fixture = TestBed.createComponent(AppComponent); + fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; + expect(compiled.querySelector('h1').textContent).toContain( 'Welcome to testSts!' ); diff --git a/projects/sample-code-flow-auth0/src/app/app.component.ts b/projects/sample-code-flow-auth0/src/app/app.component.ts index 3d1a47b4..f24ea551 100644 --- a/projects/sample-code-flow-auth0/src/app/app.component.ts +++ b/projects/sample-code-flow-auth0/src/app/app.component.ts @@ -8,7 +8,7 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; export class AppComponent implements OnInit { constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService .checkAuth() .subscribe(({ isAuthenticated }) => diff --git a/projects/sample-code-flow-auth0/src/app/home/home.component.ts b/projects/sample-code-flow-auth0/src/app/home/home.component.ts index db3773f4..55499d3c 100644 --- a/projects/sample-code-flow-auth0/src/app/home/home.component.ts +++ b/projects/sample-code-flow-auth0/src/app/home/home.component.ts @@ -7,12 +7,14 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; }) export class HomeComponent implements OnInit { configuration$ = this.oidcSecurityService.getConfiguration(); + userData$ = this.oidcSecurityService.userData$; + isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; @@ -22,35 +24,35 @@ export class HomeComponent implements OnInit { ); } - login() { + login(): void { this.oidcSecurityService.authorize(); } - refreshSession() { + refreshSession(): void { this.oidcSecurityService .forceRefreshSession() .subscribe((result) => console.log(result)); } - logout() { + logout(): void { this.oidcSecurityService .logoff() .subscribe((result) => console.log(result)); } - logoffAndRevokeTokens() { + logoffAndRevokeTokens(): void { this.oidcSecurityService .logoffAndRevokeTokens() .subscribe((result) => console.log(result)); } - revokeRefreshToken() { + revokeRefreshToken(): void { this.oidcSecurityService .revokeRefreshToken() .subscribe((result) => console.log(result)); } - revokeAccessToken() { + revokeAccessToken(): void { this.oidcSecurityService .revokeAccessToken() .subscribe((result) => console.log(result)); diff --git a/projects/sample-code-flow-auto-login/src/app/app.component.spec.ts b/projects/sample-code-flow-auto-login/src/app/app.component.spec.ts index 148e4d44..3ab1a5a0 100644 --- a/projects/sample-code-flow-auto-login/src/app/app.component.spec.ts +++ b/projects/sample-code-flow-auto-login/src/app/app.component.spec.ts @@ -11,19 +11,23 @@ describe('AppComponent', () => { it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app).toBeTruthy(); }); it(`should have as title 'sample-code-flow-auto-login'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app.title).toEqual('sample-code-flow-auto-login'); }); it('should render title in a h1 tag', () => { const fixture = TestBed.createComponent(AppComponent); + fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; + expect(compiled.querySelector('h1').textContent).toContain( 'Welcome to sample-code-flow-auto-login!' ); diff --git a/projects/sample-code-flow-auto-login/src/app/app.component.ts b/projects/sample-code-flow-auto-login/src/app/app.component.ts index bc6b4f47..ccf2d8a3 100644 --- a/projects/sample-code-flow-auto-login/src/app/app.component.ts +++ b/projects/sample-code-flow-auto-login/src/app/app.component.ts @@ -7,7 +7,7 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; styleUrls: ['./app.component.css'], }) export class AppComponent implements OnInit { - constructor(private oidcSecurityService: OidcSecurityService) {} + constructor(private readonly oidcSecurityService: OidcSecurityService) {} ngOnInit() { this.oidcSecurityService diff --git a/projects/sample-code-flow-auto-login/src/app/forbidden/forbidden.component.ts b/projects/sample-code-flow-auto-login/src/app/forbidden/forbidden.component.ts index f67a993a..fe23a1d7 100644 --- a/projects/sample-code-flow-auto-login/src/app/forbidden/forbidden.component.ts +++ b/projects/sample-code-flow-auto-login/src/app/forbidden/forbidden.component.ts @@ -8,7 +8,7 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; export class ForbiddenComponent implements OnInit { public isAuthenticated = false; - constructor(private oidcSecurityService: OidcSecurityService) {} + constructor(private readonly oidcSecurityService: OidcSecurityService) {} ngOnInit() { this.oidcSecurityService.isAuthenticated$.subscribe( diff --git a/projects/sample-code-flow-auto-login/src/app/home/home.component.ts b/projects/sample-code-flow-auto-login/src/app/home/home.component.ts index 44f8933b..dc8d964c 100644 --- a/projects/sample-code-flow-auto-login/src/app/home/home.component.ts +++ b/projects/sample-code-flow-auto-login/src/app/home/home.component.ts @@ -7,6 +7,7 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; }) export class HomeComponent implements OnInit { userData$ = this.oidcSecurityService.userData$; + isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} diff --git a/projects/sample-code-flow-azure-b2c/src/app/home/home.component.ts b/projects/sample-code-flow-azure-b2c/src/app/home/home.component.ts index 44f8933b..1dc68879 100644 --- a/projects/sample-code-flow-azure-b2c/src/app/home/home.component.ts +++ b/projects/sample-code-flow-azure-b2c/src/app/home/home.component.ts @@ -7,11 +7,12 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; }) export class HomeComponent implements OnInit { userData$ = this.oidcSecurityService.userData$; + isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; diff --git a/projects/sample-code-flow-azure-b2c/src/app/nav-menu/nav-menu.component.ts b/projects/sample-code-flow-azure-b2c/src/app/nav-menu/nav-menu.component.ts index 834f980d..8b660791 100644 --- a/projects/sample-code-flow-azure-b2c/src/app/nav-menu/nav-menu.component.ts +++ b/projects/sample-code-flow-azure-b2c/src/app/nav-menu/nav-menu.component.ts @@ -8,11 +8,12 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; }) export class NavMenuComponent implements OnInit { isExpanded = false; + isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; @@ -22,27 +23,27 @@ export class NavMenuComponent implements OnInit { ); } - login() { + login(): void { this.oidcSecurityService.authorize(); } - refreshSession() { + refreshSession(): void { this.oidcSecurityService .forceRefreshSession() .subscribe((result) => console.log(result)); } - logout() { + logout(): void { this.oidcSecurityService .logoff() .subscribe((result) => console.log(result)); } - collapse() { + collapse(): void { this.isExpanded = false; } - toggle() { + toggle(): void { this.isExpanded = !this.isExpanded; } } diff --git a/projects/sample-code-flow-azuread/src/app/app.component.ts b/projects/sample-code-flow-azuread/src/app/app.component.ts index ec6ee442..f145dffc 100644 --- a/projects/sample-code-flow-azuread/src/app/app.component.ts +++ b/projects/sample-code-flow-azuread/src/app/app.component.ts @@ -8,17 +8,17 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; export class AppComponent { constructor(public oidcSecurityService: OidcSecurityService) {} - login() { + login(): void { console.log('start login'); this.oidcSecurityService.authorize(); } - refreshSession() { + refreshSession(): void { console.log('start refreshSession'); this.oidcSecurityService.authorize(); } - logout() { + logout(): void { console.log('start logoff'); this.oidcSecurityService .logoff() diff --git a/projects/sample-code-flow-azuread/src/app/home/home.component.ts b/projects/sample-code-flow-azuread/src/app/home/home.component.ts index 44f8933b..1dc68879 100644 --- a/projects/sample-code-flow-azuread/src/app/home/home.component.ts +++ b/projects/sample-code-flow-azuread/src/app/home/home.component.ts @@ -7,11 +7,12 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; }) export class HomeComponent implements OnInit { userData$ = this.oidcSecurityService.userData$; + isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; diff --git a/projects/sample-code-flow-azuread/src/app/nav-menu/nav-menu.component.ts b/projects/sample-code-flow-azuread/src/app/nav-menu/nav-menu.component.ts index 6b9881f0..8b660791 100644 --- a/projects/sample-code-flow-azuread/src/app/nav-menu/nav-menu.component.ts +++ b/projects/sample-code-flow-azuread/src/app/nav-menu/nav-menu.component.ts @@ -13,7 +13,7 @@ export class NavMenuComponent implements OnInit { constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; @@ -23,26 +23,27 @@ export class NavMenuComponent implements OnInit { ); } - login() { + login(): void { this.oidcSecurityService.authorize(); } - refreshSession() { + refreshSession(): void { this.oidcSecurityService .forceRefreshSession() .subscribe((result) => console.log(result)); } - logout() { + logout(): void { this.oidcSecurityService .logoff() .subscribe((result) => console.log(result)); } - collapse() { + + collapse(): void { this.isExpanded = false; } - toggle() { + toggle(): void { this.isExpanded = !this.isExpanded; } } diff --git a/projects/sample-code-flow-http-config/src/app/app.component.spec.ts b/projects/sample-code-flow-http-config/src/app/app.component.spec.ts index ca37aa2b..7627c677 100644 --- a/projects/sample-code-flow-http-config/src/app/app.component.spec.ts +++ b/projects/sample-code-flow-http-config/src/app/app.component.spec.ts @@ -11,19 +11,23 @@ describe('AppComponent', () => { it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app).toBeTruthy(); }); it(`should have as title 'testSts'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app.title).toEqual('testSts'); }); it('should render title in a h1 tag', () => { const fixture = TestBed.createComponent(AppComponent); + fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; + expect(compiled.querySelector('h1').textContent).toContain( 'Welcome to testSts!' ); diff --git a/projects/sample-code-flow-http-config/src/app/app.component.ts b/projects/sample-code-flow-http-config/src/app/app.component.ts index 2af316f3..8304d267 100644 --- a/projects/sample-code-flow-http-config/src/app/app.component.ts +++ b/projects/sample-code-flow-http-config/src/app/app.component.ts @@ -13,7 +13,7 @@ import { filter } from 'rxjs/operators'; export class AppComponent implements OnInit { constructor( public oidcSecurityService: OidcSecurityService, - private eventService: PublicEventsService + private readonly eventService: PublicEventsService ) {} ngOnInit() { diff --git a/projects/sample-code-flow-http-config/src/app/auth-config.module.ts b/projects/sample-code-flow-http-config/src/app/auth-config.module.ts index a0562f6e..1924cd5f 100644 --- a/projects/sample-code-flow-http-config/src/app/auth-config.module.ts +++ b/projects/sample-code-flow-http-config/src/app/auth-config.module.ts @@ -1,4 +1,3 @@ -/* eslint-disable arrow-body-style */ import { HttpClient } from '@angular/common/http'; import { NgModule } from '@angular/core'; import { @@ -9,7 +8,7 @@ import { } from 'angular-auth-oidc-client'; import { map } from 'rxjs/operators'; -export const httpLoaderFactory = (httpClient: HttpClient) => { +export const httpLoaderFactory = (httpClient: HttpClient): StsConfigLoader => { const config$ = httpClient .get( `https://offeringsolutions-sts.azurewebsites.net/api/ClientAppSettings` diff --git a/projects/sample-code-flow-http-config/src/app/home/home.component.ts b/projects/sample-code-flow-http-config/src/app/home/home.component.ts index 3a6ce9cb..68897361 100644 --- a/projects/sample-code-flow-http-config/src/app/home/home.component.ts +++ b/projects/sample-code-flow-http-config/src/app/home/home.component.ts @@ -7,13 +7,16 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; }) export class HomeComponent implements OnInit { configuration$ = this.oidcSecurityService.getConfiguration(); + userData$ = this.oidcSecurityService.userData$; + isAuthenticated = false; + checkSessionChanged$ = this.oidcSecurityService.checkSessionChanged$; constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; @@ -23,23 +26,23 @@ export class HomeComponent implements OnInit { ); } - login() { + login(): void { this.oidcSecurityService.authorize(); } - refreshSession() { + refreshSession(): void { this.oidcSecurityService .forceRefreshSession() .subscribe((result) => console.log(result)); } - logout() { + logout(): void { this.oidcSecurityService .logoff() .subscribe((result) => console.log(result)); } - logoffLocal() { + logoffLocal(): void { this.oidcSecurityService.logoffLocal(); } } diff --git a/projects/sample-code-flow-lazy-loaded/src/app/app.component.spec.ts b/projects/sample-code-flow-lazy-loaded/src/app/app.component.spec.ts index cb1791c8..fd2aef13 100644 --- a/projects/sample-code-flow-lazy-loaded/src/app/app.component.spec.ts +++ b/projects/sample-code-flow-lazy-loaded/src/app/app.component.spec.ts @@ -13,19 +13,23 @@ describe('AppComponent', () => { it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; + expect(app).toBeTruthy(); }); it(`should have as title 'sample-code-flow-lazy-loaded'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; + expect(app.title).toEqual('sample-code-flow-lazy-loaded'); }); it('should render title', () => { const fixture = TestBed.createComponent(AppComponent); + fixture.detectChanges(); const compiled = fixture.nativeElement; + expect(compiled.querySelector('.content span').textContent).toContain( 'sample-code-flow-lazy-loaded app is running!' ); diff --git a/projects/sample-code-flow-lazy-loaded/src/app/app.component.ts b/projects/sample-code-flow-lazy-loaded/src/app/app.component.ts index c0723212..5a673e10 100644 --- a/projects/sample-code-flow-lazy-loaded/src/app/app.component.ts +++ b/projects/sample-code-flow-lazy-loaded/src/app/app.component.ts @@ -12,7 +12,7 @@ export class AppComponent { constructor(public oidcSecurityService: OidcSecurityService) { this.oidcSecurityService .checkAuth() - .subscribe(({ isAuthenticated, userData, accessToken }) => { + .subscribe(({ isAuthenticated, accessToken }) => { console.log('app authenticated', isAuthenticated); console.log(`Current access token is '${accessToken}'`); }); diff --git a/projects/sample-code-flow-lazy-loaded/src/app/lazy/lazy.component.ts b/projects/sample-code-flow-lazy-loaded/src/app/lazy/lazy.component.ts index 52155864..fa488f9c 100644 --- a/projects/sample-code-flow-lazy-loaded/src/app/lazy/lazy.component.ts +++ b/projects/sample-code-flow-lazy-loaded/src/app/lazy/lazy.component.ts @@ -8,6 +8,7 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; }) export class LazyComponent implements OnInit { isAuthenticated = false; + constructor(public oidcSecurityService: OidcSecurityService) {} ngOnInit(): void { @@ -20,11 +21,11 @@ export class LazyComponent implements OnInit { ); } - login() { + login(): void { this.oidcSecurityService.authorize(); } - logout() { + logout(): void { this.oidcSecurityService .logoff() .subscribe((result) => console.log(result)); diff --git a/projects/sample-code-flow-multi-AAD/src/app/app.component.spec.ts b/projects/sample-code-flow-multi-AAD/src/app/app.component.spec.ts index ca37aa2b..7627c677 100644 --- a/projects/sample-code-flow-multi-AAD/src/app/app.component.spec.ts +++ b/projects/sample-code-flow-multi-AAD/src/app/app.component.spec.ts @@ -11,19 +11,23 @@ describe('AppComponent', () => { it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app).toBeTruthy(); }); it(`should have as title 'testSts'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app.title).toEqual('testSts'); }); it('should render title in a h1 tag', () => { const fixture = TestBed.createComponent(AppComponent); + fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; + expect(compiled.querySelector('h1').textContent).toContain( 'Welcome to testSts!' ); diff --git a/projects/sample-code-flow-multi-AAD/src/app/app.component.ts b/projects/sample-code-flow-multi-AAD/src/app/app.component.ts index e0491ddd..57612a8e 100644 --- a/projects/sample-code-flow-multi-AAD/src/app/app.component.ts +++ b/projects/sample-code-flow-multi-AAD/src/app/app.component.ts @@ -8,7 +8,7 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; export class AppComponent implements OnInit { constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService .checkAuthMultiple() .subscribe(([{ isAuthenticated, userData, accessToken }]) => { diff --git a/projects/sample-code-flow-multi-AAD/src/app/home/home.component.ts b/projects/sample-code-flow-multi-AAD/src/app/home/home.component.ts index 2221d2eb..c979d65f 100644 --- a/projects/sample-code-flow-multi-AAD/src/app/home/home.component.ts +++ b/projects/sample-code-flow-multi-AAD/src/app/home/home.component.ts @@ -7,28 +7,30 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; }) export class HomeComponent { configurations = this.oidcSecurityService.getConfigurations(); + userData$ = this.oidcSecurityService.userData$; + isAuthenticated$ = this.oidcSecurityService.isAuthenticated$; constructor(public oidcSecurityService: OidcSecurityService) {} - login(configId: string | undefined) { + login(configId: string | undefined): void { this.oidcSecurityService.authorize(configId); } - forceRefreshSession() { + forceRefreshSession(): void { this.oidcSecurityService .forceRefreshSession() .subscribe((result) => console.warn(result)); } - logout(configId: string | undefined) { + logout(configId: string | undefined): void { this.oidcSecurityService .logoff(configId) .subscribe((result) => console.log(result)); } - refreshSession(configId: string | undefined) { + refreshSession(configId: string | undefined): void { this.oidcSecurityService .forceRefreshSession(undefined, configId) .subscribe((result) => console.log(result)); diff --git a/projects/sample-code-flow-multi-Auth0-ID4-popup/src/app/app.component.spec.ts b/projects/sample-code-flow-multi-Auth0-ID4-popup/src/app/app.component.spec.ts index ca37aa2b..7627c677 100644 --- a/projects/sample-code-flow-multi-Auth0-ID4-popup/src/app/app.component.spec.ts +++ b/projects/sample-code-flow-multi-Auth0-ID4-popup/src/app/app.component.spec.ts @@ -11,19 +11,23 @@ describe('AppComponent', () => { it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app).toBeTruthy(); }); it(`should have as title 'testSts'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app.title).toEqual('testSts'); }); it('should render title in a h1 tag', () => { const fixture = TestBed.createComponent(AppComponent); + fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; + expect(compiled.querySelector('h1').textContent).toContain( 'Welcome to testSts!' ); diff --git a/projects/sample-code-flow-multi-Auth0-ID4-popup/src/app/app.component.ts b/projects/sample-code-flow-multi-Auth0-ID4-popup/src/app/app.component.ts index e0491ddd..57612a8e 100644 --- a/projects/sample-code-flow-multi-Auth0-ID4-popup/src/app/app.component.ts +++ b/projects/sample-code-flow-multi-Auth0-ID4-popup/src/app/app.component.ts @@ -8,7 +8,7 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; export class AppComponent implements OnInit { constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService .checkAuthMultiple() .subscribe(([{ isAuthenticated, userData, accessToken }]) => { diff --git a/projects/sample-code-flow-multi-Auth0-ID4-popup/src/app/home/home.component.ts b/projects/sample-code-flow-multi-Auth0-ID4-popup/src/app/home/home.component.ts index eb9f372e..8a50ed33 100644 --- a/projects/sample-code-flow-multi-Auth0-ID4-popup/src/app/home/home.component.ts +++ b/projects/sample-code-flow-multi-Auth0-ID4-popup/src/app/home/home.component.ts @@ -14,11 +14,11 @@ export class HomeComponent { constructor(public oidcSecurityService: OidcSecurityService) {} - login(configId: string) { + login(configId: string): void { this.oidcSecurityService.authorize(configId); } - loginWithPopup(configId: string | undefined) { + loginWithPopup(configId: string | undefined): void { this.oidcSecurityService .authorizeWithPopUp(undefined, undefined, configId) .subscribe(({ isAuthenticated, userData, accessToken, errorMessage }) => { @@ -29,29 +29,29 @@ export class HomeComponent { }); } - openWindow() { + openWindow(): void { window.open('/', '_blank'); } - forceRefreshSession() { + forceRefreshSession(): void { this.oidcSecurityService .forceRefreshSession() .subscribe((result) => console.warn(result)); } - logout(configId: string | undefined) { + logout(configId: string | undefined): void { this.oidcSecurityService .logoff(configId) .subscribe((result) => console.log(result)); } - refreshSessionId4(configId: string | undefined) { + refreshSessionId4(configId: string | undefined): void { this.oidcSecurityService .forceRefreshSession(undefined, configId) .subscribe((result) => console.log(result)); } - refreshSessionAuth0(configId: string | undefined) { + refreshSessionAuth0(configId: string | undefined): void { this.oidcSecurityService .forceRefreshSession( { scope: 'openid profile offline_access auth0-user-api-spa' }, @@ -60,13 +60,13 @@ export class HomeComponent { .subscribe((result) => console.log(result)); } - logoffAndRevokeTokens(configId: string | undefined) { + logoffAndRevokeTokens(configId: string | undefined): void { this.oidcSecurityService .logoffAndRevokeTokens(configId) .subscribe((result) => console.log(result)); } - revokeRefreshToken(configId: string | undefined) { + revokeRefreshToken(configId: string | undefined): void { this.oidcSecurityService .revokeRefreshToken(null, configId) .subscribe((result) => console.log(result)); diff --git a/projects/sample-code-flow-multi-Auth0-ID4/src/app/app.component.spec.ts b/projects/sample-code-flow-multi-Auth0-ID4/src/app/app.component.spec.ts index ca37aa2b..7627c677 100644 --- a/projects/sample-code-flow-multi-Auth0-ID4/src/app/app.component.spec.ts +++ b/projects/sample-code-flow-multi-Auth0-ID4/src/app/app.component.spec.ts @@ -11,19 +11,23 @@ describe('AppComponent', () => { it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app).toBeTruthy(); }); it(`should have as title 'testSts'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app.title).toEqual('testSts'); }); it('should render title in a h1 tag', () => { const fixture = TestBed.createComponent(AppComponent); + fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; + expect(compiled.querySelector('h1').textContent).toContain( 'Welcome to testSts!' ); diff --git a/projects/sample-code-flow-multi-Auth0-ID4/src/app/app.component.ts b/projects/sample-code-flow-multi-Auth0-ID4/src/app/app.component.ts index 03387930..57612a8e 100644 --- a/projects/sample-code-flow-multi-Auth0-ID4/src/app/app.component.ts +++ b/projects/sample-code-flow-multi-Auth0-ID4/src/app/app.component.ts @@ -8,8 +8,7 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; export class AppComponent implements OnInit { constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { - //this.oidcSecurityService.preloadAuthWellKnownDocument().subscribe(); + ngOnInit(): void { this.oidcSecurityService .checkAuthMultiple() .subscribe(([{ isAuthenticated, userData, accessToken }]) => { diff --git a/projects/sample-code-flow-multi-Auth0-ID4/src/app/home/home.component.ts b/projects/sample-code-flow-multi-Auth0-ID4/src/app/home/home.component.ts index 4a00c5e2..c065b5d2 100644 --- a/projects/sample-code-flow-multi-Auth0-ID4/src/app/home/home.component.ts +++ b/projects/sample-code-flow-multi-Auth0-ID4/src/app/home/home.component.ts @@ -14,29 +14,29 @@ export class HomeComponent { constructor(public oidcSecurityService: OidcSecurityService) {} - login(configId: string | undefined) { + login(configId: string | undefined): void { this.oidcSecurityService.authorize(configId); } - forceRefreshSession() { + forceRefreshSession(): void { this.oidcSecurityService .forceRefreshSession() .subscribe((result) => console.warn(result)); } - logout(configId: string | undefined) { + logout(configId: string | undefined): void { this.oidcSecurityService .logoff(configId) .subscribe((result) => console.log(result)); } - refreshSessionId4(configId: string | undefined) { + refreshSessionId4(configId: string | undefined): void { this.oidcSecurityService .forceRefreshSession(undefined, configId) .subscribe((result) => console.log(result)); } - refreshSessionAuth0(configId: string | undefined) { + refreshSessionAuth0(configId: string | undefined): void { this.oidcSecurityService .forceRefreshSession( { scope: 'openid profile offline_access auth0-user-api-spa' }, @@ -45,13 +45,13 @@ export class HomeComponent { .subscribe((result) => console.log(result)); } - logoffAndRevokeTokens(configId: string | undefined) { + logoffAndRevokeTokens(configId: string | undefined): void { this.oidcSecurityService .logoffAndRevokeTokens(configId) .subscribe((result) => console.log(result)); } - revokeRefreshToken(configId: string | undefined) { + revokeRefreshToken(configId: string | undefined): void { this.oidcSecurityService .revokeRefreshToken(null, configId) .subscribe((result) => console.log(result)); diff --git a/projects/sample-code-flow-multi-Azure-B2C/src/app/app.component.spec.ts b/projects/sample-code-flow-multi-Azure-B2C/src/app/app.component.spec.ts index ca37aa2b..7627c677 100644 --- a/projects/sample-code-flow-multi-Azure-B2C/src/app/app.component.spec.ts +++ b/projects/sample-code-flow-multi-Azure-B2C/src/app/app.component.spec.ts @@ -11,19 +11,23 @@ describe('AppComponent', () => { it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app).toBeTruthy(); }); it(`should have as title 'testSts'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app.title).toEqual('testSts'); }); it('should render title in a h1 tag', () => { const fixture = TestBed.createComponent(AppComponent); + fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; + expect(compiled.querySelector('h1').textContent).toContain( 'Welcome to testSts!' ); diff --git a/projects/sample-code-flow-multi-Azure-B2C/src/app/app.component.ts b/projects/sample-code-flow-multi-Azure-B2C/src/app/app.component.ts index e0491ddd..57612a8e 100644 --- a/projects/sample-code-flow-multi-Azure-B2C/src/app/app.component.ts +++ b/projects/sample-code-flow-multi-Azure-B2C/src/app/app.component.ts @@ -8,7 +8,7 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; export class AppComponent implements OnInit { constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService .checkAuthMultiple() .subscribe(([{ isAuthenticated, userData, accessToken }]) => { diff --git a/projects/sample-code-flow-multi-Azure-B2C/src/app/home/home.component.ts b/projects/sample-code-flow-multi-Azure-B2C/src/app/home/home.component.ts index 3539e329..8c77cf29 100644 --- a/projects/sample-code-flow-multi-Azure-B2C/src/app/home/home.component.ts +++ b/projects/sample-code-flow-multi-Azure-B2C/src/app/home/home.component.ts @@ -7,26 +7,28 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; }) export class HomeComponent { configurations = this.oidcSecurityService.getConfigurations(); + userData$ = this.oidcSecurityService.userData$; + isAuthenticated$ = this.oidcSecurityService.isAuthenticated$; constructor(public oidcSecurityService: OidcSecurityService) {} - login(configId: string | undefined) { + login(configId: string | undefined): void { this.oidcSecurityService.authorize(configId); } - forceRefreshSession() { + forceRefreshSession(): void { this.oidcSecurityService .forceRefreshSession() .subscribe((result) => console.warn(result)); } - logout(configId: string | undefined) { + logout(configId: string | undefined): void { this.oidcSecurityService.logoff(configId); } - refreshSession(configId: string | undefined) { + refreshSession(configId: string | undefined): void { this.oidcSecurityService .forceRefreshSession(undefined, configId) .subscribe((result) => console.log(result)); diff --git a/projects/sample-code-flow-multi-iframe/src/app/app.component.spec.ts b/projects/sample-code-flow-multi-iframe/src/app/app.component.spec.ts index ca37aa2b..7627c677 100644 --- a/projects/sample-code-flow-multi-iframe/src/app/app.component.spec.ts +++ b/projects/sample-code-flow-multi-iframe/src/app/app.component.spec.ts @@ -11,19 +11,23 @@ describe('AppComponent', () => { it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app).toBeTruthy(); }); it(`should have as title 'testSts'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app.title).toEqual('testSts'); }); it('should render title in a h1 tag', () => { const fixture = TestBed.createComponent(AppComponent); + fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; + expect(compiled.querySelector('h1').textContent).toContain( 'Welcome to testSts!' ); diff --git a/projects/sample-code-flow-multi-iframe/src/app/home/home.component.ts b/projects/sample-code-flow-multi-iframe/src/app/home/home.component.ts index d5658451..f5ecb8a2 100644 --- a/projects/sample-code-flow-multi-iframe/src/app/home/home.component.ts +++ b/projects/sample-code-flow-multi-iframe/src/app/home/home.component.ts @@ -7,7 +7,9 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; }) export class HomeComponent { configurations = this.oidcSecurityService.getConfigurations(); + userData$ = this.oidcSecurityService.userData$; + isAuthenticated$ = this.oidcSecurityService.isAuthenticated$; constructor(public oidcSecurityService: OidcSecurityService) {} diff --git a/projects/sample-code-flow-refresh-tokens/src/app/app.component.spec.ts b/projects/sample-code-flow-refresh-tokens/src/app/app.component.spec.ts index ca37aa2b..7627c677 100644 --- a/projects/sample-code-flow-refresh-tokens/src/app/app.component.spec.ts +++ b/projects/sample-code-flow-refresh-tokens/src/app/app.component.spec.ts @@ -11,19 +11,23 @@ describe('AppComponent', () => { it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app).toBeTruthy(); }); it(`should have as title 'testSts'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app.title).toEqual('testSts'); }); it('should render title in a h1 tag', () => { const fixture = TestBed.createComponent(AppComponent); + fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; + expect(compiled.querySelector('h1').textContent).toContain( 'Welcome to testSts!' ); diff --git a/projects/sample-code-flow-refresh-tokens/src/app/app.component.ts b/projects/sample-code-flow-refresh-tokens/src/app/app.component.ts index aeed09d3..6ce19352 100644 --- a/projects/sample-code-flow-refresh-tokens/src/app/app.component.ts +++ b/projects/sample-code-flow-refresh-tokens/src/app/app.component.ts @@ -8,10 +8,10 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; export class AppComponent implements OnInit { constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService .checkAuth() - .subscribe(({ isAuthenticated, userData, accessToken }) => { + .subscribe(({ isAuthenticated, accessToken }) => { console.log('app authenticated', isAuthenticated); console.log(`Current access token is '${accessToken}'`); }); diff --git a/projects/sample-code-flow-refresh-tokens/src/app/home/home.component.ts b/projects/sample-code-flow-refresh-tokens/src/app/home/home.component.ts index 4579d6f7..55499d3c 100644 --- a/projects/sample-code-flow-refresh-tokens/src/app/home/home.component.ts +++ b/projects/sample-code-flow-refresh-tokens/src/app/home/home.component.ts @@ -7,11 +7,14 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; }) export class HomeComponent implements OnInit { configuration$ = this.oidcSecurityService.getConfiguration(); + userData$ = this.oidcSecurityService.userData$; + isAuthenticated = false; + constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; @@ -21,35 +24,35 @@ export class HomeComponent implements OnInit { ); } - login() { + login(): void { this.oidcSecurityService.authorize(); } - refreshSession() { + refreshSession(): void { this.oidcSecurityService .forceRefreshSession() .subscribe((result) => console.log(result)); } - logout() { + logout(): void { this.oidcSecurityService .logoff() .subscribe((result) => console.log(result)); } - logoffAndRevokeTokens() { + logoffAndRevokeTokens(): void { this.oidcSecurityService .logoffAndRevokeTokens() .subscribe((result) => console.log(result)); } - revokeRefreshToken() { + revokeRefreshToken(): void { this.oidcSecurityService .revokeRefreshToken() .subscribe((result) => console.log(result)); } - revokeAccessToken() { + revokeAccessToken(): void { this.oidcSecurityService .revokeAccessToken() .subscribe((result) => console.log(result)); diff --git a/projects/sample-code-flow-standalone/src/app/app.component.spec.ts b/projects/sample-code-flow-standalone/src/app/app.component.spec.ts index 6731cff5..5635392c 100644 --- a/projects/sample-code-flow-standalone/src/app/app.component.spec.ts +++ b/projects/sample-code-flow-standalone/src/app/app.component.spec.ts @@ -11,19 +11,23 @@ describe('AppComponent', () => { it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app).toBeTruthy(); }); it(`should have as title 'sample-code-flow-standalone'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app.title).toEqual('sample-code-flow-standalone'); }); it('should render title in a h1 tag', () => { const fixture = TestBed.createComponent(AppComponent); + fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; + expect(compiled.querySelector('h1').textContent).toContain( 'Welcome to sample-code-flow-standalone!' ); diff --git a/projects/sample-code-flow-standalone/src/app/app.component.ts b/projects/sample-code-flow-standalone/src/app/app.component.ts index 2427505f..b89f41da 100644 --- a/projects/sample-code-flow-standalone/src/app/app.component.ts +++ b/projects/sample-code-flow-standalone/src/app/app.component.ts @@ -1,6 +1,6 @@ import { Component, OnInit } from '@angular/core'; -import { OidcSecurityService } from 'angular-auth-oidc-client'; import { RouterOutlet } from '@angular/router'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; import { NavigationComponent } from './navigation/navigation.component'; @Component({ @@ -11,28 +11,28 @@ import { NavigationComponent } from './navigation/navigation.component'; imports: [RouterOutlet, NavigationComponent], }) export class AppComponent implements OnInit { - constructor(private oidcSecurityService: OidcSecurityService) {} + constructor(private readonly oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService .checkAuth() - .subscribe(({ isAuthenticated, userData, accessToken }) => { + .subscribe(({ isAuthenticated, accessToken }) => { console.log('app authenticated', isAuthenticated); console.log(`Current access token is '${accessToken}'`); }); } - login() { + login(): void { console.log('start login'); this.oidcSecurityService.authorize(); } - refreshSession() { + refreshSession(): void { console.log('start refreshSession'); this.oidcSecurityService.authorize(); } - logout() { + logout(): void { console.log('start logoff'); this.oidcSecurityService .logoff() diff --git a/projects/sample-code-flow-standalone/src/app/forbidden/forbidden.component.ts b/projects/sample-code-flow-standalone/src/app/forbidden/forbidden.component.ts index 066e7e63..6433011e 100644 --- a/projects/sample-code-flow-standalone/src/app/forbidden/forbidden.component.ts +++ b/projects/sample-code-flow-standalone/src/app/forbidden/forbidden.component.ts @@ -9,9 +9,9 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; export class ForbiddenComponent implements OnInit { public isAuthenticated = false; - constructor(private oidcSecurityService: OidcSecurityService) {} + constructor(private readonly oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; diff --git a/projects/sample-code-flow-standalone/src/app/home/home.component.ts b/projects/sample-code-flow-standalone/src/app/home/home.component.ts index 06ee5539..e5543f69 100644 --- a/projects/sample-code-flow-standalone/src/app/home/home.component.ts +++ b/projects/sample-code-flow-standalone/src/app/home/home.component.ts @@ -10,11 +10,12 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; }) export class HomeComponent implements OnInit { userData$ = this.oidcSecurityService.userData$; + isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; diff --git a/projects/sample-code-flow-standalone/src/app/navigation/navigation.component.ts b/projects/sample-code-flow-standalone/src/app/navigation/navigation.component.ts index f1dd5621..ce8811b8 100644 --- a/projects/sample-code-flow-standalone/src/app/navigation/navigation.component.ts +++ b/projects/sample-code-flow-standalone/src/app/navigation/navigation.component.ts @@ -15,7 +15,7 @@ export class NavigationComponent implements OnInit { constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; @@ -25,15 +25,15 @@ export class NavigationComponent implements OnInit { ); } - login() { + login(): void { this.oidcSecurityService.authorize(); } - refreshSession() { + refreshSession(): void { this.oidcSecurityService.authorize(); } - logout() { + logout(): void { this.oidcSecurityService .logoff() .subscribe((result) => console.log(result)); diff --git a/projects/sample-implicit-flow-google/src/app/app.component.spec.ts b/projects/sample-implicit-flow-google/src/app/app.component.spec.ts index d8e18bd9..5fd32df1 100644 --- a/projects/sample-implicit-flow-google/src/app/app.component.spec.ts +++ b/projects/sample-implicit-flow-google/src/app/app.component.spec.ts @@ -13,19 +13,23 @@ describe('AppComponent', () => { it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; + expect(app).toBeTruthy(); }); it(`should have as title 'sample-implicit-flow-google'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; + expect(app.title).toEqual('sample-implicit-flow-google'); }); it('should render title', () => { const fixture = TestBed.createComponent(AppComponent); + fixture.detectChanges(); const compiled = fixture.nativeElement; + expect(compiled.querySelector('.content span').textContent).toContain( 'sample-implicit-flow-google app is running!' ); diff --git a/projects/sample-implicit-flow-google/src/app/app.component.ts b/projects/sample-implicit-flow-google/src/app/app.component.ts index 4384a02a..f98a1bf6 100644 --- a/projects/sample-implicit-flow-google/src/app/app.component.ts +++ b/projects/sample-implicit-flow-google/src/app/app.component.ts @@ -1,4 +1,4 @@ -import { Component, OnDestroy, OnInit } from '@angular/core'; +import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { OidcSecurityService } from 'angular-auth-oidc-client'; @@ -6,13 +6,13 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; selector: 'app-root', templateUrl: 'app.component.html', }) -export class AppComponent implements OnInit, OnDestroy { +export class AppComponent implements OnInit { constructor( public oidcSecurityService: OidcSecurityService, - private router: Router + private readonly router: Router ) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService .checkAuth() @@ -29,26 +29,24 @@ export class AppComponent implements OnInit, OnDestroy { }); } - ngOnDestroy(): void {} - - login() { + login(): void { console.log('start login'); this.oidcSecurityService.authorize(); } - refreshSession() { + refreshSession(): void { console.log('start refreshSession'); this.oidcSecurityService.authorize(); } - logout() { + logout(): void { console.log('start logoff'); this.oidcSecurityService .logoff() .subscribe((result) => console.log(result)); } - private navigateToStoredEndpoint() { + private navigateToStoredEndpoint(): void { const path = this.read('redirect'); if (this.router.url === path) { @@ -64,6 +62,7 @@ export class AppComponent implements OnInit, OnDestroy { private read(key: string): any { const data = localStorage.getItem(key); + if (data != null) { return JSON.parse(data); } diff --git a/projects/sample-implicit-flow-google/src/app/auto-login/auto-login.component.ts b/projects/sample-implicit-flow-google/src/app/auto-login/auto-login.component.ts index ad692e5b..397c4d63 100644 --- a/projects/sample-implicit-flow-google/src/app/auto-login/auto-login.component.ts +++ b/projects/sample-implicit-flow-google/src/app/auto-login/auto-login.component.ts @@ -8,7 +8,7 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; export class AutoLoginComponent implements OnInit { constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService .checkAuth() .subscribe(() => this.oidcSecurityService.authorize()); diff --git a/projects/sample-implicit-flow-google/src/app/home/home.component.ts b/projects/sample-implicit-flow-google/src/app/home/home.component.ts index 44f8933b..1dc68879 100644 --- a/projects/sample-implicit-flow-google/src/app/home/home.component.ts +++ b/projects/sample-implicit-flow-google/src/app/home/home.component.ts @@ -7,11 +7,12 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; }) export class HomeComponent implements OnInit { userData$ = this.oidcSecurityService.userData$; + isAuthenticated = false; constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; diff --git a/projects/sample-implicit-flow-google/src/app/navigation/navigation.component.ts b/projects/sample-implicit-flow-google/src/app/navigation/navigation.component.ts index 5dd55eca..65ceb8f6 100644 --- a/projects/sample-implicit-flow-google/src/app/navigation/navigation.component.ts +++ b/projects/sample-implicit-flow-google/src/app/navigation/navigation.component.ts @@ -10,7 +10,7 @@ export class NavigationComponent implements OnInit { constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; @@ -20,15 +20,15 @@ export class NavigationComponent implements OnInit { ); } - login() { + login(): void { this.oidcSecurityService.authorize(); } - refreshSession() { + refreshSession(): void { this.oidcSecurityService.authorize(); } - logout() { + logout(): void { this.oidcSecurityService .logoff() .subscribe((result) => console.log(result)); diff --git a/projects/sample-implicit-flow-silent-renew/src/app/app.component.spec.ts b/projects/sample-implicit-flow-silent-renew/src/app/app.component.spec.ts index ca37aa2b..7627c677 100644 --- a/projects/sample-implicit-flow-silent-renew/src/app/app.component.spec.ts +++ b/projects/sample-implicit-flow-silent-renew/src/app/app.component.spec.ts @@ -11,19 +11,23 @@ describe('AppComponent', () => { it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app).toBeTruthy(); }); it(`should have as title 'testSts'`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; + expect(app.title).toEqual('testSts'); }); it('should render title in a h1 tag', () => { const fixture = TestBed.createComponent(AppComponent); + fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; + expect(compiled.querySelector('h1').textContent).toContain( 'Welcome to testSts!' ); diff --git a/projects/sample-implicit-flow-silent-renew/src/app/app.component.ts b/projects/sample-implicit-flow-silent-renew/src/app/app.component.ts index 263e8425..0dc5f04c 100644 --- a/projects/sample-implicit-flow-silent-renew/src/app/app.component.ts +++ b/projects/sample-implicit-flow-silent-renew/src/app/app.component.ts @@ -8,7 +8,7 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; export class AppComponent implements OnInit { constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService .checkAuthIncludingServer() .subscribe((isAuthenticated) => diff --git a/projects/sample-implicit-flow-silent-renew/src/app/home/home.component.ts b/projects/sample-implicit-flow-silent-renew/src/app/home/home.component.ts index f636ee13..915333fb 100644 --- a/projects/sample-implicit-flow-silent-renew/src/app/home/home.component.ts +++ b/projects/sample-implicit-flow-silent-renew/src/app/home/home.component.ts @@ -7,13 +7,16 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; }) export class HomeComponent implements OnInit { configuration$ = this.oidcSecurityService.getConfiguration(); + userData$ = this.oidcSecurityService.userData$; + isAuthenticated = false; + checkSessionChanged$ = this.oidcSecurityService.checkSessionChanged$; constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; @@ -22,23 +25,24 @@ export class HomeComponent implements OnInit { } ); } - login() { + + login(): void { console.log('start login'); this.oidcSecurityService.authorize(); } - refreshSessionCheckSession() { + refreshSessionCheckSession(): void { console.log('start refreshSession'); this.oidcSecurityService.authorize(); } - forceRefreshSession() { + forceRefreshSession(): void { this.oidcSecurityService .forceRefreshSession() .subscribe((result) => console.log(result)); } - logout() { + logout(): void { console.log('start logoff'); this.oidcSecurityService .logoff() From 8b45cf250fef3135ff8e2d5236fb0ab4bb590567 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Mon, 18 Mar 2024 11:50:24 +0100 Subject: [PATCH 44/56] Update linting command and fix method signatures --- .github/workflows/build.yml | 2 +- lefthook.yml | 2 +- package.json | 1 - .../src/app/app.component.ts | 10 +++++----- .../src/app/forbidden/forbidden.component.ts | 2 +- .../src/app/home/home.component.ts | 2 +- .../src/app/navigation/navigation.component.ts | 8 ++++---- .../src/app/app.component.ts | 12 +++++------- .../src/app/app.component.ts | 2 +- .../src/app/home/home.component.ts | 6 +++--- 10 files changed, 22 insertions(+), 25 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ed4324e5..018fb921 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -28,7 +28,7 @@ jobs: run: npm ci - name: Linting Frontend - run: npm run lint-lib + run: npm run lint - name: Testing Frontend run: npm run test-lib-ci diff --git a/lefthook.yml b/lefthook.yml index cfcc9684..68db6e29 100644 --- a/lefthook.yml +++ b/lefthook.yml @@ -16,7 +16,7 @@ pre-commit: run: npm run check-blockwords lint: - run: npm run lint-lib + run: npm run lint # # pre-commit: # parallel: true diff --git a/package.json b/package.json index db4ff403..e4a5e051 100644 --- a/package.json +++ b/package.json @@ -18,7 +18,6 @@ "build-lib-prod": "ng build angular-auth-oidc-client --configuration production && npm run schematics-build && npm run copy-files", "test-lib": "ng test angular-auth-oidc-client --code-coverage", "test-lib-ci": "ng test angular-auth-oidc-client --watch=false --browsers=ChromeHeadlessNoSandbox --code-coverage", - "lint-lib": "ng lint angular-auth-oidc-client", "pack-lib": "npm run build-lib-prod && npm pack ./dist/angular-auth-oidc-client", "publish-lib": "npm run build-lib-prod && npm publish ./dist/angular-auth-oidc-client", "publish-lib-next": "npm run build-lib && npm publish --tag next ./dist/angular-auth-oidc-client", diff --git a/projects/sample-code-flow-auto-login/src/app/app.component.ts b/projects/sample-code-flow-auto-login/src/app/app.component.ts index ccf2d8a3..c36e3f09 100644 --- a/projects/sample-code-flow-auto-login/src/app/app.component.ts +++ b/projects/sample-code-flow-auto-login/src/app/app.component.ts @@ -9,26 +9,26 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; export class AppComponent implements OnInit { constructor(private readonly oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService .checkAuth() - .subscribe(({ isAuthenticated, userData, accessToken }) => { + .subscribe(({ isAuthenticated, accessToken }) => { console.log('app authenticated', isAuthenticated); console.log(`Current access token is '${accessToken}'`); }); } - login() { + login(): void { console.log('start login'); this.oidcSecurityService.authorize(); } - refreshSession() { + refreshSession(): void { console.log('start refreshSession'); this.oidcSecurityService.authorize(); } - logout() { + logout(): void { console.log('start logoff'); this.oidcSecurityService .logoff() diff --git a/projects/sample-code-flow-auto-login/src/app/forbidden/forbidden.component.ts b/projects/sample-code-flow-auto-login/src/app/forbidden/forbidden.component.ts index fe23a1d7..97de4338 100644 --- a/projects/sample-code-flow-auto-login/src/app/forbidden/forbidden.component.ts +++ b/projects/sample-code-flow-auto-login/src/app/forbidden/forbidden.component.ts @@ -10,7 +10,7 @@ export class ForbiddenComponent implements OnInit { constructor(private readonly oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; diff --git a/projects/sample-code-flow-auto-login/src/app/home/home.component.ts b/projects/sample-code-flow-auto-login/src/app/home/home.component.ts index dc8d964c..1dc68879 100644 --- a/projects/sample-code-flow-auto-login/src/app/home/home.component.ts +++ b/projects/sample-code-flow-auto-login/src/app/home/home.component.ts @@ -12,7 +12,7 @@ export class HomeComponent implements OnInit { constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; diff --git a/projects/sample-code-flow-auto-login/src/app/navigation/navigation.component.ts b/projects/sample-code-flow-auto-login/src/app/navigation/navigation.component.ts index cba9bcb8..09062d66 100644 --- a/projects/sample-code-flow-auto-login/src/app/navigation/navigation.component.ts +++ b/projects/sample-code-flow-auto-login/src/app/navigation/navigation.component.ts @@ -11,7 +11,7 @@ export class NavigationComponent implements OnInit { constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService.isAuthenticated$.subscribe( ({ isAuthenticated }) => { this.isAuthenticated = isAuthenticated; @@ -21,15 +21,15 @@ export class NavigationComponent implements OnInit { ); } - login() { + login(): void { this.oidcSecurityService.authorize(); } - refreshSession() { + refreshSession(): void { this.oidcSecurityService.authorize(); } - logout() { + logout(): void { this.oidcSecurityService .logoff() .subscribe((result) => console.log(result)); diff --git a/projects/sample-code-flow-http-config/src/app/app.component.ts b/projects/sample-code-flow-http-config/src/app/app.component.ts index 8304d267..37035e71 100644 --- a/projects/sample-code-flow-http-config/src/app/app.component.ts +++ b/projects/sample-code-flow-http-config/src/app/app.component.ts @@ -16,15 +16,13 @@ export class AppComponent implements OnInit { private readonly eventService: PublicEventsService ) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService .checkAuth() - .subscribe( - ({ isAuthenticated, userData, accessToken, idToken, configId }) => { - console.log('app authenticated', isAuthenticated); - console.log(`Current access token is '${accessToken}'`); - } - ); + .subscribe(({ isAuthenticated, accessToken }) => { + console.log('app authenticated', isAuthenticated); + console.log(`Current access token is '${accessToken}'`); + }); this.eventService .registerForEvents() diff --git a/projects/sample-code-flow-multi-iframe/src/app/app.component.ts b/projects/sample-code-flow-multi-iframe/src/app/app.component.ts index e0491ddd..57612a8e 100644 --- a/projects/sample-code-flow-multi-iframe/src/app/app.component.ts +++ b/projects/sample-code-flow-multi-iframe/src/app/app.component.ts @@ -8,7 +8,7 @@ import { OidcSecurityService } from 'angular-auth-oidc-client'; export class AppComponent implements OnInit { constructor(public oidcSecurityService: OidcSecurityService) {} - ngOnInit() { + ngOnInit(): void { this.oidcSecurityService .checkAuthMultiple() .subscribe(([{ isAuthenticated, userData, accessToken }]) => { diff --git a/projects/sample-code-flow-multi-iframe/src/app/home/home.component.ts b/projects/sample-code-flow-multi-iframe/src/app/home/home.component.ts index f5ecb8a2..04b8e972 100644 --- a/projects/sample-code-flow-multi-iframe/src/app/home/home.component.ts +++ b/projects/sample-code-flow-multi-iframe/src/app/home/home.component.ts @@ -14,17 +14,17 @@ export class HomeComponent { constructor(public oidcSecurityService: OidcSecurityService) {} - login(configId: string | undefined) { + login(configId: string | undefined): void { this.oidcSecurityService.authorize(configId); } - forceRefreshSession() { + forceRefreshSession(): void { this.oidcSecurityService .forceRefreshSession() .subscribe((result) => console.warn(result)); } - logout(configId: string | undefined) { + logout(configId: string | undefined): void { this.oidcSecurityService.logoff(configId); } } From 8c9439052abcf142f740cf73e748276a2e1d021e Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Mon, 18 Mar 2024 12:01:52 +0100 Subject: [PATCH 45/56] Exclude spec.ts files from compilation --- projects/sample-code-flow-multi-iframe/tsconfig.app.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/projects/sample-code-flow-multi-iframe/tsconfig.app.json b/projects/sample-code-flow-multi-iframe/tsconfig.app.json index c3c48375..82b3d1b3 100644 --- a/projects/sample-code-flow-multi-iframe/tsconfig.app.json +++ b/projects/sample-code-flow-multi-iframe/tsconfig.app.json @@ -6,5 +6,5 @@ "types": [] }, "files": ["src/main.ts", "src/polyfills.ts"], - "include": ["src/**/*.d.ts"] + "exclude": ["**/*.spec.ts"] } From af12588659867d52b5593c8c972293391bcb9994 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Mon, 18 Mar 2024 13:09:38 +0100 Subject: [PATCH 46/56] Add tsconfigRootDir to ESLint configuration --- .eslintrc.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.eslintrc.json b/.eslintrc.json index a4d8e5d7..0f6cbb07 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -6,7 +6,8 @@ "files": ["*.ts"], "parserOptions": { "project": ["tsconfig.json"], - "createDefaultProgram": true + "createDefaultProgram": true, + "tsconfigRootDir": "./" }, "extends": [ "plugin:@angular-eslint/recommended", From 4a97bcb6e19d84376343f8f116ae5063fd1e933d Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Mon, 18 Mar 2024 13:12:09 +0100 Subject: [PATCH 47/56] Update linting command for library --- .github/workflows/build.yml | 4 ++-- lefthook.yml | 2 +- package.json | 1 + 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 018fb921..62b0ad80 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -27,8 +27,8 @@ jobs: - name: Installing Dependencies run: npm ci - - name: Linting Frontend - run: npm run lint + - name: Linting Library + run: npm run lint-lib - name: Testing Frontend run: npm run test-lib-ci diff --git a/lefthook.yml b/lefthook.yml index 68db6e29..cfcc9684 100644 --- a/lefthook.yml +++ b/lefthook.yml @@ -16,7 +16,7 @@ pre-commit: run: npm run check-blockwords lint: - run: npm run lint + run: npm run lint-lib # # pre-commit: # parallel: true diff --git a/package.json b/package.json index e4a5e051..db4ff403 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "build-lib-prod": "ng build angular-auth-oidc-client --configuration production && npm run schematics-build && npm run copy-files", "test-lib": "ng test angular-auth-oidc-client --code-coverage", "test-lib-ci": "ng test angular-auth-oidc-client --watch=false --browsers=ChromeHeadlessNoSandbox --code-coverage", + "lint-lib": "ng lint angular-auth-oidc-client", "pack-lib": "npm run build-lib-prod && npm pack ./dist/angular-auth-oidc-client", "publish-lib": "npm run build-lib-prod && npm publish ./dist/angular-auth-oidc-client", "publish-lib-next": "npm run build-lib && npm publish --tag next ./dist/angular-auth-oidc-client", From d1b3fc040f9e18659b3aec96d27afdbd2e03e488 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Mon, 18 Mar 2024 19:35:24 +0100 Subject: [PATCH 48/56] Update configuration service in unit tests --- .gitignore | 1 + .../src/lib/auth.module.spec.ts | 16 +----- .../auto-login-all-routes.guard.spec.ts | 7 +-- .../auto-login-partial-routes.guard.spec.ts | 7 +-- .../periodically-token-check.service.spec.ts | 40 ++++---------- .../lib/interceptor/auth.interceptor.spec.ts | 16 ++---- .../src/lib/oidc.security.service.spec.ts | 55 +++++-------------- .../src/lib/provide-auth.spec.ts | 12 +--- 8 files changed, 41 insertions(+), 113 deletions(-) diff --git a/.gitignore b/.gitignore index aa45d5da..20529ac0 100644 --- a/.gitignore +++ b/.gitignore @@ -50,3 +50,4 @@ Thumbs.db debug.log /.husky +/.nx diff --git a/projects/angular-auth-oidc-client/src/lib/auth.module.spec.ts b/projects/angular-auth-oidc-client/src/lib/auth.module.spec.ts index b471ef8c..9327ba19 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth.module.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth.module.spec.ts @@ -1,6 +1,6 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { of } from 'rxjs'; -import { mockClass } from '../test/auto-mock'; +import { mockProvider } from '../test/auto-mock'; import { PASSED_CONFIG } from './auth-config'; import { AuthModule } from './auth.module'; import { ConfigurationService } from './config/config.service'; @@ -17,12 +17,7 @@ describe('AuthModule', () => { beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [AuthModule.forRoot({ config: { authority: 'something' } })], - providers: [ - { - provide: ConfigurationService, - useClass: mockClass(ConfigurationService), - }, - ], + providers: [mockProvider(ConfigurationService)], }).compileComponents(); })); @@ -54,12 +49,7 @@ describe('AuthModule', () => { }, }), ], - providers: [ - { - provide: ConfigurationService, - useClass: mockClass(ConfigurationService), - }, - ], + providers: [mockProvider(ConfigurationService)], }).compileComponents(); })); diff --git a/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-all-routes.guard.spec.ts b/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-all-routes.guard.spec.ts index 185546a4..d1a62559 100644 --- a/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-all-routes.guard.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-all-routes.guard.spec.ts @@ -6,7 +6,7 @@ import { } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { Observable, of } from 'rxjs'; -import { mockClass } from '../../test/auto-mock'; +import { mockClass, mockProvider } from '../../test/auto-mock'; import { CheckAuthService } from '../auth-state/check-auth.service'; import { ConfigurationService } from '../config/config.service'; import { LoginResponse } from '../login/login-response'; @@ -33,10 +33,7 @@ describe(`AutoLoginAllRoutesGuard`, () => { provide: StoragePersistenceService, useClass: mockClass(StoragePersistenceService), }, - { - provide: ConfigurationService, - useClass: mockClass(ConfigurationService), - }, + mockProvider(ConfigurationService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-partial-routes.guard.spec.ts b/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-partial-routes.guard.spec.ts index 1618f276..c86c9521 100644 --- a/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-partial-routes.guard.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-partial-routes.guard.spec.ts @@ -6,7 +6,7 @@ import { } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { of } from 'rxjs'; -import { mockClass } from '../../test/auto-mock'; +import { mockClass, mockProvider } from '../../test/auto-mock'; import { AuthStateService } from '../auth-state/auth-state.service'; import { CheckAuthService } from '../auth-state/check-auth.service'; import { ConfigurationService } from '../config/config.service'; @@ -37,10 +37,7 @@ describe(`AutoLoginPartialRoutesGuard`, () => { provide: CheckAuthService, useClass: mockClass(CheckAuthService), }, - { - provide: ConfigurationService, - useClass: mockClass(ConfigurationService), - }, + mockProvider(ConfigurationService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/callback/periodically-token-check.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/callback/periodically-token-check.service.spec.ts index 16c81aac..6941af51 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/periodically-token-check.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/periodically-token-check.service.spec.ts @@ -1,6 +1,6 @@ import { fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { of, throwError } from 'rxjs'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { AuthStateService } from '../auth-state/auth-state.service'; import { ConfigurationService } from '../config/config.service'; import { OpenIdConfiguration } from '../config/openid-configuration'; @@ -35,36 +35,18 @@ describe('PeriodicallyTokenCheckService', () => { TestBed.configureTestingModule({ imports: [], providers: [ - { - provide: ResetAuthDataService, - useClass: mockClass(ResetAuthDataService), - }, + mockProvider(ResetAuthDataService), FlowHelper, - { provide: FlowsDataService, useClass: mockClass(FlowsDataService) }, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - { provide: UserService, useClass: mockClass(UserService) }, - { provide: AuthStateService, useClass: mockClass(AuthStateService) }, - { - provide: RefreshSessionIframeService, - useClass: mockClass(RefreshSessionIframeService), - }, - { - provide: RefreshSessionRefreshTokenService, - useClass: mockClass(RefreshSessionRefreshTokenService), - }, + mockProvider(FlowsDataService), + mockProvider(LoggerService), + mockProvider(UserService), + mockProvider(AuthStateService), + mockProvider(RefreshSessionIframeService), + mockProvider(RefreshSessionRefreshTokenService), IntervalService, - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, - { - provide: PublicEventsService, - useClass: mockClass(PublicEventsService), - }, - { - provide: ConfigurationService, - useClass: mockClass(ConfigurationService), - }, + mockProvider(StoragePersistenceService), + mockProvider(PublicEventsService), + mockProvider(ConfigurationService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/interceptor/auth.interceptor.spec.ts b/projects/angular-auth-oidc-client/src/lib/interceptor/auth.interceptor.spec.ts index 13a5b46e..c047155d 100644 --- a/projects/angular-auth-oidc-client/src/lib/interceptor/auth.interceptor.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/interceptor/auth.interceptor.spec.ts @@ -1,6 +1,6 @@ import { - HttpClient, HTTP_INTERCEPTORS, + HttpClient, provideHttpClient, withInterceptors, } from '@angular/common/http'; @@ -10,11 +10,11 @@ import { provideHttpClientTesting, } from '@angular/common/http/testing'; import { TestBed, waitForAsync } from '@angular/core/testing'; -import { mockClass } from '../../test/auto-mock'; +import { mockClass, mockProvider } from '../../test/auto-mock'; import { AuthStateService } from '../auth-state/auth-state.service'; import { ConfigurationService } from '../config/config.service'; import { LoggerService } from '../logging/logger.service'; -import { authInterceptor, AuthInterceptor } from './auth.interceptor'; +import { AuthInterceptor, authInterceptor } from './auth.interceptor'; import { ClosestMatchingRouteService } from './closest-matching-route.service'; describe(`AuthHttpInterceptor`, () => { @@ -40,10 +40,7 @@ describe(`AuthHttpInterceptor`, () => { provide: LoggerService, useClass: mockClass(LoggerService), }, - { - provide: ConfigurationService, - useClass: mockClass(ConfigurationService), - }, + mockProvider(ConfigurationService), ], }); @@ -73,10 +70,7 @@ describe(`AuthHttpInterceptor`, () => { provide: LoggerService, useClass: mockClass(LoggerService), }, - { - provide: ConfigurationService, - useClass: mockClass(ConfigurationService), - }, + mockProvider(ConfigurationService), ], }); diff --git a/projects/angular-auth-oidc-client/src/lib/oidc.security.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/oidc.security.service.spec.ts index 1105b93b..ffadcedb 100644 --- a/projects/angular-auth-oidc-client/src/lib/oidc.security.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/oidc.security.service.spec.ts @@ -1,6 +1,6 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { Observable, of } from 'rxjs'; -import { mockClass } from '../test/auto-mock'; +import { mockProvider } from '../test/auto-mock'; import { AuthenticatedResult } from './auth-state/auth-result'; import { AuthStateService } from './auth-state/auth-state.service'; import { CheckAuthService } from './auth-state/check-auth.service'; @@ -40,46 +40,19 @@ describe('OidcSecurityService', () => { imports: [], providers: [ OidcSecurityService, - { - provide: CheckSessionService, - useClass: mockClass(CheckSessionService), - }, - { - provide: CheckAuthService, - useClass: mockClass(CheckAuthService), - }, - { - provide: UserService, - useClass: mockClass(UserService), - }, - { - provide: TokenHelperService, - useClass: mockClass(TokenHelperService), - }, - { - provide: ConfigurationService, - useClass: mockClass(ConfigurationService), - }, - { - provide: AuthStateService, - useClass: mockClass(AuthStateService), - }, - { provide: FlowsDataService, useClass: mockClass(FlowsDataService) }, - { provide: CallbackService, useClass: mockClass(CallbackService) }, - { - provide: LogoffRevocationService, - useClass: mockClass(LogoffRevocationService), - }, - { provide: LoginService, useClass: mockClass(LoginService) }, - { - provide: RefreshSessionService, - useClass: mockClass(RefreshSessionService), - }, - { provide: UrlService, useClass: mockClass(UrlService) }, - { - provide: AuthWellKnownService, - useClass: mockClass(AuthWellKnownService), - }, + mockProvider(CheckSessionService), + mockProvider(CheckAuthService), + mockProvider(UserService), + mockProvider(TokenHelperService), + mockProvider(ConfigurationService), + mockProvider(AuthStateService), + mockProvider(FlowsDataService), + mockProvider(CallbackService), + mockProvider(LogoffRevocationService), + mockProvider(LoginService), + mockProvider(RefreshSessionService), + mockProvider(UrlService), + mockProvider(AuthWellKnownService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/provide-auth.spec.ts b/projects/angular-auth-oidc-client/src/lib/provide-auth.spec.ts index e5c74d3b..06d0bfe2 100644 --- a/projects/angular-auth-oidc-client/src/lib/provide-auth.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/provide-auth.spec.ts @@ -1,6 +1,6 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { of } from 'rxjs'; -import { mockClass } from '../test/auto-mock'; +import { mockProvider } from '../test/auto-mock'; import { PASSED_CONFIG } from './auth-config'; import { ConfigurationService } from './config/config.service'; import { @@ -18,10 +18,7 @@ describe('provideAuth', () => { TestBed.configureTestingModule({ providers: [ provideAuth({ config: { authority: 'something' } }), - { - provide: ConfigurationService, - useClass: mockClass(ConfigurationService), - }, + mockProvider(ConfigurationService), ], }).compileComponents(); })); @@ -48,10 +45,7 @@ describe('provideAuth', () => { useFactory: () => new StsConfigHttpLoader(of({})), }, }), - { - provide: ConfigurationService, - useClass: mockClass(ConfigurationService), - }, + mockProvider(ConfigurationService), ], }).compileComponents(); })); From 6f31e0a368718c83a3dc6ab2edd8923c820b2d26 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Mon, 18 Mar 2024 20:01:43 +0100 Subject: [PATCH 49/56] Update service providers in unit tests --- .../lib/auth-state/auth-state.service.spec.ts | 16 ++----- .../lib/auth-state/check-auth.service.spec.ts | 47 +++++-------------- .../auto-login-all-routes.guard.spec.ts | 17 ++----- .../auto-login-partial-routes.guard.spec.ts | 19 ++------ .../lib/auto-login/auto-login.service.spec.ts | 10 +--- .../src/lib/callback/callback.service.spec.ts | 14 ++---- .../code-flow-callback.service.spec.ts | 6 +-- .../implicit-flow-callback.service.spec.ts | 6 +-- ...resh-session-refresh-token.service.spec.ts | 11 ++--- .../callback/refresh-session.service.spec.ts | 35 ++++---------- .../src/lib/flows/flows.service.spec.ts | 37 ++++----------- .../lib/login/par/par-login.service.spec.ts | 42 ++++------------- .../login/popup/popup-login.service.spec.ts | 20 +++----- .../response-type-validation.service.spec.ts | 12 ++--- .../standard/standard-login.service.spec.ts | 20 +++----- .../token-validation.service.spec.ts | 12 ++--- 16 files changed, 90 insertions(+), 234 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.spec.ts index 2ecf471b..7f1f239a 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/auth-state.service.spec.ts @@ -1,6 +1,6 @@ import { TestBed } from '@angular/core/testing'; import { Observable } from 'rxjs'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { LoggerService } from '../logging/logger.service'; import { EventTypes } from '../public-events/event-types'; import { PublicEventsService } from '../public-events/public-events.service'; @@ -21,16 +21,10 @@ describe('Auth State Service', () => { providers: [ AuthStateService, PublicEventsService, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - { - provide: TokenValidationService, - useClass: mockClass(TokenValidationService), - }, - { provide: PlatformProvider, useClass: mockClass(PlatformProvider) }, - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, + mockProvider(LoggerService), + mockProvider(TokenValidationService), + mockProvider(PlatformProvider), + mockProvider(StoragePersistenceService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts index 5178bed5..a4de0cb0 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts @@ -1,7 +1,7 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { of, throwError } from 'rxjs'; -import { mockClass } from '../../test/auto-mock'; +import { mockClass, mockProvider } from '../../test/auto-mock'; import { AutoLoginService } from '../auto-login/auto-login.service'; import { CallbackService } from '../callback/callback.service'; import { PeriodicallyTokenCheckService } from '../callback/periodically-token-check.service'; @@ -44,45 +44,24 @@ describe('CheckAuthService', () => { TestBed.configureTestingModule({ imports: [RouterTestingModule], providers: [ - { - provide: CheckSessionService, - useClass: mockClass(CheckSessionService), - }, - { - provide: SilentRenewService, - useClass: mockClass(SilentRenewService), - }, - { provide: UserService, useClass: mockClass(UserService) }, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - { provide: AuthStateService, useClass: mockClass(AuthStateService) }, - { provide: CallbackService, useClass: mockClass(CallbackService) }, - { - provide: RefreshSessionService, - useClass: mockClass(RefreshSessionService), - }, - { - provide: PeriodicallyTokenCheckService, - useClass: mockClass(PeriodicallyTokenCheckService), - }, - { provide: PopUpService, useClass: mockClass(PopUpService) }, + mockProvider(CheckSessionService), + mockProvider(SilentRenewService), + mockProvider(UserService), + mockProvider(LoggerService), + mockProvider(AuthStateService), + mockProvider(CallbackService), + mockProvider(RefreshSessionService), + mockProvider(PeriodicallyTokenCheckService), + mockProvider(PopUpService), + mockProvider(CurrentUrlService), + mockProvider(PublicEventsService), { provide: StsConfigLoader, useClass: mockClass(StsConfigStaticLoader), }, - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, AutoLoginService, CheckAuthService, - { - provide: CurrentUrlService, - useClass: mockClass(CurrentUrlService), - }, - { - provide: PublicEventsService, - useClass: mockClass(PublicEventsService), - }, + mockProvider(StoragePersistenceService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-all-routes.guard.spec.ts b/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-all-routes.guard.spec.ts index d1a62559..0bdb75db 100644 --- a/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-all-routes.guard.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-all-routes.guard.spec.ts @@ -6,7 +6,7 @@ import { } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { Observable, of } from 'rxjs'; -import { mockClass, mockProvider } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { CheckAuthService } from '../auth-state/check-auth.service'; import { ConfigurationService } from '../config/config.service'; import { LoginResponse } from '../login/login-response'; @@ -21,18 +21,9 @@ describe(`AutoLoginAllRoutesGuard`, () => { imports: [RouterTestingModule], providers: [ AutoLoginService, - { - provide: CheckAuthService, - useClass: mockClass(CheckAuthService), - }, - { - provide: LoginService, - useClass: mockClass(LoginService), - }, - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, + mockProvider(CheckAuthService), + mockProvider(LoginService), + mockProvider(StoragePersistenceService), mockProvider(ConfigurationService), ], }); diff --git a/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-partial-routes.guard.spec.ts b/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-partial-routes.guard.spec.ts index c86c9521..8dce2831 100644 --- a/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-partial-routes.guard.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login-partial-routes.guard.spec.ts @@ -6,7 +6,7 @@ import { } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { of } from 'rxjs'; -import { mockClass, mockProvider } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { AuthStateService } from '../auth-state/auth-state.service'; import { CheckAuthService } from '../auth-state/check-auth.service'; import { ConfigurationService } from '../config/config.service'; @@ -24,19 +24,10 @@ describe(`AutoLoginPartialRoutesGuard`, () => { imports: [RouterTestingModule], providers: [ AutoLoginService, - { provide: AuthStateService, useClass: mockClass(AuthStateService) }, - { - provide: LoginService, - useClass: mockClass(LoginService), - }, - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, - { - provide: CheckAuthService, - useClass: mockClass(CheckAuthService), - }, + mockProvider(AuthStateService), + mockProvider(LoginService), + mockProvider(StoragePersistenceService), + mockProvider(CheckAuthService), mockProvider(ConfigurationService), ], }); diff --git a/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login.service.spec.ts index 33c1780b..b0f685ae 100644 --- a/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auto-login/auto-login.service.spec.ts @@ -1,7 +1,7 @@ import { TestBed } from '@angular/core/testing'; import { Router } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { StoragePersistenceService } from '../storage/storage-persistence.service'; import { AutoLoginService } from './auto-login.service'; @@ -13,13 +13,7 @@ describe('AutoLoginService ', () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [RouterTestingModule], - providers: [ - AutoLoginService, - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, - ], + providers: [AutoLoginService, mockProvider(StoragePersistenceService)], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/callback/callback.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/callback/callback.service.spec.ts index 44fd0ebd..93490ac7 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/callback.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/callback.service.spec.ts @@ -1,6 +1,6 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { Observable, of } from 'rxjs'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { CallbackContext } from '../flows/callback-context'; import { FlowHelper } from '../utils/flowHelper/flow-helper.service'; import { UrlService } from '../utils/url/url.service'; @@ -20,16 +20,10 @@ describe('CallbackService ', () => { imports: [], providers: [ CallbackService, - { provide: UrlService, useClass: mockClass(UrlService) }, + mockProvider(UrlService), FlowHelper, - { - provide: ImplicitFlowCallbackService, - useClass: mockClass(ImplicitFlowCallbackService), - }, - { - provide: CodeFlowCallbackService, - useClass: mockClass(CodeFlowCallbackService), - }, + mockProvider(ImplicitFlowCallbackService), + mockProvider(CodeFlowCallbackService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.spec.ts index e2171941..37656c61 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.spec.ts @@ -2,7 +2,7 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { Router } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { of, throwError } from 'rxjs'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { CallbackContext } from '../flows/callback-context'; import { FlowsDataService } from '../flows/flows-data.service'; import { FlowsService } from '../flows/flows.service'; @@ -21,8 +21,8 @@ describe('CodeFlowCallbackService ', () => { imports: [RouterTestingModule], providers: [ CodeFlowCallbackService, - { provide: FlowsService, useClass: mockClass(FlowsService) }, - { provide: FlowsDataService, useClass: mockClass(FlowsDataService) }, + mockProvider(FlowsService), + mockProvider(FlowsDataService), IntervalService, ], }); diff --git a/projects/angular-auth-oidc-client/src/lib/callback/implicit-flow-callback.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/callback/implicit-flow-callback.service.spec.ts index 233e38cd..608d4824 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/implicit-flow-callback.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/implicit-flow-callback.service.spec.ts @@ -2,7 +2,7 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { Router } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { of, throwError } from 'rxjs'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { CallbackContext } from '../flows/callback-context'; import { FlowsDataService } from '../flows/flows-data.service'; import { FlowsService } from '../flows/flows.service'; @@ -21,8 +21,8 @@ describe('ImplicitFlowCallbackService ', () => { imports: [RouterTestingModule], providers: [ ImplicitFlowCallbackService, - { provide: FlowsService, useClass: mockClass(FlowsService) }, - { provide: FlowsDataService, useClass: mockClass(FlowsDataService) }, + mockProvider(FlowsService), + mockProvider(FlowsDataService), IntervalService, ], }); diff --git a/projects/angular-auth-oidc-client/src/lib/callback/refresh-session-refresh-token.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/callback/refresh-session-refresh-token.service.spec.ts index 4db3c62b..0b432f2d 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/refresh-session-refresh-token.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/refresh-session-refresh-token.service.spec.ts @@ -1,6 +1,6 @@ import { fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { of, throwError } from 'rxjs'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { CallbackContext } from '../flows/callback-context'; import { FlowsService } from '../flows/flows.service'; import { ResetAuthDataService } from '../flows/reset-auth-data.service'; @@ -19,12 +19,9 @@ describe('RefreshSessionRefreshTokenService', () => { imports: [], providers: [ RefreshSessionRefreshTokenService, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - { provide: FlowsService, useClass: mockClass(FlowsService) }, - { - provide: ResetAuthDataService, - useClass: mockClass(ResetAuthDataService), - }, + mockProvider(LoggerService), + mockProvider(FlowsService), + mockProvider(ResetAuthDataService), IntervalService, ], }); diff --git a/projects/angular-auth-oidc-client/src/lib/callback/refresh-session.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/callback/refresh-session.service.spec.ts index cf209f1b..4a384dd0 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/refresh-session.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/refresh-session.service.spec.ts @@ -1,7 +1,7 @@ import { fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { of, throwError } from 'rxjs'; import { delay } from 'rxjs/operators'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { AuthStateService } from '../auth-state/auth-state.service'; import { AuthWellKnownService } from '../config/auth-well-known/auth-well-known.service'; import { CallbackContext } from '../flows/callback-context'; @@ -34,31 +34,16 @@ describe('RefreshSessionService ', () => { imports: [], providers: [ FlowHelper, - { provide: FlowsDataService, useClass: mockClass(FlowsDataService) }, + mockProvider(FlowsDataService), RefreshSessionService, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - { - provide: SilentRenewService, - useClass: mockClass(SilentRenewService), - }, - { provide: AuthStateService, useClass: mockClass(AuthStateService) }, - { - provide: AuthWellKnownService, - useClass: mockClass(AuthWellKnownService), - }, - { - provide: RefreshSessionIframeService, - useClass: mockClass(RefreshSessionIframeService), - }, - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, - { - provide: RefreshSessionRefreshTokenService, - useClass: mockClass(RefreshSessionRefreshTokenService), - }, - { provide: UserService, useClass: mockClass(UserService) }, + mockProvider(LoggerService), + mockProvider(SilentRenewService), + mockProvider(AuthStateService), + mockProvider(AuthWellKnownService), + mockProvider(RefreshSessionIframeService), + mockProvider(StoragePersistenceService), + mockProvider(RefreshSessionRefreshTokenService), + mockProvider(UserService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/flows/flows.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/flows.service.spec.ts index e81e4da4..34c33cef 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/flows.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/flows.service.spec.ts @@ -1,6 +1,6 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { of } from 'rxjs'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { CallbackContext } from './callback-context'; import { CodeFlowCallbackHandlerService } from './callback-handling/code-flow-callback-handler.service'; import { HistoryJwtKeysCallbackHandlerService } from './callback-handling/history-jwt-keys-callback-handler.service'; @@ -25,34 +25,13 @@ describe('Flows Service', () => { TestBed.configureTestingModule({ providers: [ FlowsService, - { - provide: CodeFlowCallbackHandlerService, - useClass: mockClass(CodeFlowCallbackHandlerService), - }, - { - provide: ImplicitFlowCallbackHandlerService, - useClass: mockClass(ImplicitFlowCallbackHandlerService), - }, - { - provide: HistoryJwtKeysCallbackHandlerService, - useClass: mockClass(HistoryJwtKeysCallbackHandlerService), - }, - { - provide: UserCallbackHandlerService, - useClass: mockClass(UserCallbackHandlerService), - }, - { - provide: StateValidationCallbackHandlerService, - useClass: mockClass(StateValidationCallbackHandlerService), - }, - { - provide: RefreshSessionCallbackHandlerService, - useClass: mockClass(RefreshSessionCallbackHandlerService), - }, - { - provide: RefreshTokenCallbackHandlerService, - useClass: mockClass(RefreshTokenCallbackHandlerService), - }, + mockProvider(CodeFlowCallbackHandlerService), + mockProvider(ImplicitFlowCallbackHandlerService), + mockProvider(HistoryJwtKeysCallbackHandlerService), + mockProvider(UserCallbackHandlerService), + mockProvider(StateValidationCallbackHandlerService), + mockProvider(RefreshSessionCallbackHandlerService), + mockProvider(RefreshTokenCallbackHandlerService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/login/par/par-login.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/par/par-login.service.spec.ts index b96bc572..02e0a99d 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/par/par-login.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/par/par-login.service.spec.ts @@ -1,6 +1,6 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { of } from 'rxjs'; -import { mockClass } from '../../../test/auto-mock'; +import { mockProvider } from '../../../test/auto-mock'; import { CheckAuthService } from '../../auth-state/check-auth.service'; import { AuthWellKnownService } from '../../config/auth-well-known/auth-well-known.service'; import { LoggerService } from '../../logging/logger.service'; @@ -29,38 +29,14 @@ describe('ParLoginService', () => { TestBed.configureTestingModule({ providers: [ ParLoginService, - { - provide: LoggerService, - useClass: mockClass(LoggerService), - }, - { - provide: ResponseTypeValidationService, - useClass: mockClass(ResponseTypeValidationService), - }, - { - provide: UrlService, - useClass: mockClass(UrlService), - }, - { - provide: RedirectService, - useClass: mockClass(RedirectService), - }, - { - provide: AuthWellKnownService, - useClass: mockClass(AuthWellKnownService), - }, - { - provide: PopUpService, - useClass: mockClass(PopUpService), - }, - { - provide: CheckAuthService, - useClass: mockClass(CheckAuthService), - }, - { - provide: ParService, - useClass: mockClass(ParService), - }, + mockProvider(LoggerService), + mockProvider(ResponseTypeValidationService), + mockProvider(UrlService), + mockProvider(RedirectService), + mockProvider(AuthWellKnownService), + mockProvider(PopUpService), + mockProvider(CheckAuthService), + mockProvider(ParService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/login/popup/popup-login.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/popup/popup-login.service.spec.ts index e63e0f27..9d8116e3 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/popup/popup-login.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/popup/popup-login.service.spec.ts @@ -1,7 +1,7 @@ import { CommonModule } from '@angular/common'; import { TestBed, waitForAsync } from '@angular/core/testing'; import { of } from 'rxjs'; -import { mockClass } from '../../../test/auto-mock'; +import { mockProvider } from '../../../test/auto-mock'; import { CheckAuthService } from '../../auth-state/check-auth.service'; import { AuthWellKnownService } from '../../config/auth-well-known/auth-well-known.service'; import { LoggerService } from '../../logging/logger.service'; @@ -26,18 +26,12 @@ describe('PopUpLoginService', () => { imports: [CommonModule], providers: [ PopUpLoginService, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - { - provide: ResponseTypeValidationService, - useClass: mockClass(ResponseTypeValidationService), - }, - { provide: UrlService, useClass: mockClass(UrlService) }, - { - provide: AuthWellKnownService, - useClass: mockClass(AuthWellKnownService), - }, - { provide: PopUpService, useClass: mockClass(PopUpService) }, - { provide: CheckAuthService, useClass: mockClass(CheckAuthService) }, + mockProvider(LoggerService), + mockProvider(ResponseTypeValidationService), + mockProvider(UrlService), + mockProvider(AuthWellKnownService), + mockProvider(PopUpService), + mockProvider(CheckAuthService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/login/response-type-validation/response-type-validation.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/response-type-validation/response-type-validation.service.spec.ts index a9ed28cc..679841c1 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/response-type-validation/response-type-validation.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/response-type-validation/response-type-validation.service.spec.ts @@ -1,5 +1,5 @@ import { TestBed } from '@angular/core/testing'; -import { mockClass } from '../../../test/auto-mock'; +import { mockProvider } from '../../../test/auto-mock'; import { LoggerService } from '../../logging/logger.service'; import { FlowHelper } from '../../utils/flowHelper/flow-helper.service'; import { ResponseTypeValidationService } from './response-type-validation.service'; @@ -13,14 +13,8 @@ describe('ResponseTypeValidationService', () => { imports: [], providers: [ ResponseTypeValidationService, - { - provide: LoggerService, - useClass: mockClass(LoggerService), - }, - { - provide: FlowHelper, - useClass: mockClass(FlowHelper), - }, + mockProvider(LoggerService), + mockProvider(FlowHelper), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/login/standard/standard-login.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/standard/standard-login.service.spec.ts index 4f0de92a..4313ccc2 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/standard/standard-login.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/standard/standard-login.service.spec.ts @@ -1,6 +1,6 @@ import { fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { of } from 'rxjs'; -import { mockClass } from '../../../test/auto-mock'; +import { mockProvider } from '../../../test/auto-mock'; import { AuthWellKnownService } from '../../config/auth-well-known/auth-well-known.service'; import { FlowsDataService } from '../../flows/flows-data.service'; import { LoggerService } from '../../logging/logger.service'; @@ -23,18 +23,12 @@ describe('StandardLoginService', () => { imports: [], providers: [ StandardLoginService, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - { - provide: ResponseTypeValidationService, - useClass: mockClass(ResponseTypeValidationService), - }, - { provide: UrlService, useClass: mockClass(UrlService) }, - { provide: RedirectService, useClass: mockClass(RedirectService) }, - { - provide: AuthWellKnownService, - useClass: mockClass(AuthWellKnownService), - }, - { provide: FlowsDataService, useClass: mockClass(FlowsDataService) }, + mockProvider(LoggerService), + mockProvider(ResponseTypeValidationService), + mockProvider(UrlService), + mockProvider(RedirectService), + mockProvider(AuthWellKnownService), + mockProvider(FlowsDataService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/validation/token-validation.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/validation/token-validation.service.spec.ts index f83b7e15..f2abacba 100644 --- a/projects/angular-auth-oidc-client/src/lib/validation/token-validation.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/validation/token-validation.service.spec.ts @@ -1,6 +1,6 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { of } from 'rxjs'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { JwkExtractor } from '../extractors/jwk.extractor'; import { LoggerService } from '../logging/logger.service'; import { CryptoService } from '../utils/crypto/crypto.service'; @@ -19,14 +19,8 @@ describe('TokenValidationService', () => { imports: [], providers: [ TokenValidationService, - { - provide: LoggerService, - useClass: mockClass(LoggerService), - }, - { - provide: TokenHelperService, - useClass: mockClass(TokenHelperService), - }, + mockProvider(LoggerService), + mockProvider(TokenHelperService), JwkExtractor, JwkWindowCryptoService, JwtWindowCryptoService, From d0bce960a4a244da7db8d76e240f5dc3c024f2fc Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Mon, 18 Mar 2024 20:21:01 +0100 Subject: [PATCH 50/56] Update service providers in unit tests --- .../auth-well-known-data.service.spec.ts | 6 ++--- .../auth-well-known.service.spec.ts | 12 +++------ .../src/lib/config/config.service.spec.ts | 22 ++++------------ .../config-validation.service.spec.ts | 7 ++--- ...code-flow-callback-handler.service.spec.ts | 20 +++++--------- ...-jwt-keys-callback-handler.service.spec.ts | 23 +++++----------- ...icit-flow-callback-handler.service.spec.ts | 11 +++----- ...h-session-callback-handler.service.spec.ts | 8 +++--- ...esh-token-callback-handler.service.spec.ts | 13 ++++------ ...alidation-callback-handler.service.spec.ts | 16 ++++-------- .../user-callback-handler.service.spec.ts | 15 +++++------ .../src/lib/flows/flows-data.service.spec.ts | 9 +++---- .../lib/flows/random/random.service.spec.ts | 8 ++---- .../lib/flows/reset-auth-data.service.spec.ts | 10 +++---- .../lib/flows/signin-key-data.service.spec.ts | 11 +++----- .../lib/iframe/check-session.service.spec.ts | 11 +++----- .../refresh-session-iframe.service.spec.ts | 11 +++----- .../lib/iframe/silent-renew.service.spec.ts | 20 +++++--------- .../lib/interceptor/auth.interceptor.spec.ts | 16 ++++-------- .../closest-matching-route.service.spec.ts | 10 ++----- .../src/lib/login/login.service.spec.ts | 18 +++++-------- .../src/lib/login/par/par.service.spec.ts | 23 ++++------------ .../src/lib/login/popup/popup.service.spec.ts | 10 +++---- .../logoff-revocation.service.spec.ts | 26 ++++++------------- .../state-validation.service.spec.ts | 19 +++----------- 25 files changed, 113 insertions(+), 242 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known-data.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known-data.service.spec.ts index afa97cc3..b901cc2c 100644 --- a/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known-data.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known-data.service.spec.ts @@ -1,6 +1,6 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { of, throwError } from 'rxjs'; -import { mockClass } from '../../../test/auto-mock'; +import { mockProvider } from '../../../test/auto-mock'; import { createRetriableStream } from '../../../test/create-retriable-stream.helper'; import { DataService } from '../../api/data.service'; import { LoggerService } from '../../logging/logger.service'; @@ -33,8 +33,8 @@ describe('AuthWellKnownDataService', () => { TestBed.configureTestingModule({ providers: [ AuthWellKnownDataService, - { provide: DataService, useClass: mockClass(DataService) }, - { provide: LoggerService, useClass: mockClass(LoggerService) }, + mockProvider(DataService), + mockProvider(LoggerService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known.service.spec.ts index c8152dfb..2e61fd57 100644 --- a/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/config/auth-well-known/auth-well-known.service.spec.ts @@ -1,6 +1,6 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { of, throwError } from 'rxjs'; -import { mockClass } from '../../../test/auto-mock'; +import { mockProvider } from '../../../test/auto-mock'; import { EventTypes } from '../../public-events/event-types'; import { PublicEventsService } from '../../public-events/public-events.service'; import { StoragePersistenceService } from '../../storage/storage-persistence.service'; @@ -18,14 +18,8 @@ describe('AuthWellKnownService', () => { providers: [ AuthWellKnownService, PublicEventsService, - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, - { - provide: AuthWellKnownDataService, - useClass: mockClass(AuthWellKnownDataService), - }, + mockProvider(AuthWellKnownDataService), + mockProvider(StoragePersistenceService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/config/config.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/config/config.service.spec.ts index 55982128..c06585a0 100644 --- a/projects/angular-auth-oidc-client/src/lib/config/config.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/config/config.service.spec.ts @@ -1,6 +1,6 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { of } from 'rxjs'; -import { mockClass } from '../../test/auto-mock'; +import { mockClass, mockProvider } from '../../test/auto-mock'; import { LoggerService } from '../logging/logger.service'; import { EventTypes } from '../public-events/event-types'; import { PublicEventsService } from '../public-events/public-events.service'; @@ -25,24 +25,12 @@ describe('Configuration Service', () => { TestBed.configureTestingModule({ providers: [ ConfigurationService, - { - provide: LoggerService, - useClass: mockClass(LoggerService), - }, + mockProvider(LoggerService), PublicEventsService, - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, + mockProvider(StoragePersistenceService), ConfigValidationService, - { - provide: PlatformProvider, - useClass: mockClass(PlatformProvider), - }, - { - provide: AuthWellKnownService, - useClass: mockClass(AuthWellKnownService), - }, + mockProvider(PlatformProvider), + mockProvider(AuthWellKnownService), { provide: StsConfigLoader, useClass: mockClass(StsConfigStaticLoader), diff --git a/projects/angular-auth-oidc-client/src/lib/config/validation/config-validation.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/config/validation/config-validation.service.spec.ts index 45646377..7bf529fb 100644 --- a/projects/angular-auth-oidc-client/src/lib/config/validation/config-validation.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/config/validation/config-validation.service.spec.ts @@ -1,5 +1,5 @@ import { TestBed } from '@angular/core/testing'; -import { mockClass } from '../../../test/auto-mock'; +import { mockProvider } from '../../../test/auto-mock'; import { LogLevel } from '../../logging/log-level'; import { LoggerService } from '../../logging/logger.service'; import { OpenIdConfiguration } from '../openid-configuration'; @@ -12,10 +12,7 @@ describe('Config Validation Service', () => { beforeEach(() => { TestBed.configureTestingModule({ - providers: [ - ConfigValidationService, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - ], + providers: [ConfigValidationService, mockProvider(LoggerService)], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/code-flow-callback-handler.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/code-flow-callback-handler.service.spec.ts index fec93a98..09ff2515 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/code-flow-callback-handler.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/code-flow-callback-handler.service.spec.ts @@ -1,7 +1,7 @@ import { HttpErrorResponse, HttpHeaders } from '@angular/common/http'; import { TestBed, waitForAsync } from '@angular/core/testing'; import { of, throwError } from 'rxjs'; -import { mockClass } from '../../../test/auto-mock'; +import { mockProvider } from '../../../test/auto-mock'; import { createRetriableStream } from '../../../test/create-retriable-stream.helper'; import { DataService } from '../../api/data.service'; import { LoggerService } from '../../logging/logger.service'; @@ -23,18 +23,12 @@ describe('CodeFlowCallbackHandlerService', () => { TestBed.configureTestingModule({ providers: [ CodeFlowCallbackHandlerService, - { provide: UrlService, useClass: mockClass(UrlService) }, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - { - provide: TokenValidationService, - useClass: mockClass(TokenValidationService), - }, - { provide: FlowsDataService, useClass: mockClass(FlowsDataService) }, - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, - { provide: DataService, useClass: mockClass(DataService) }, + mockProvider(UrlService), + mockProvider(LoggerService), + mockProvider(TokenValidationService), + mockProvider(FlowsDataService), + mockProvider(StoragePersistenceService), + mockProvider(DataService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/history-jwt-keys-callback-handler.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/history-jwt-keys-callback-handler.service.spec.ts index 0a26cea9..754420c2 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/history-jwt-keys-callback-handler.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/history-jwt-keys-callback-handler.service.spec.ts @@ -1,6 +1,6 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { of, throwError } from 'rxjs'; -import { mockClass } from '../../../test/auto-mock'; +import { mockProvider } from '../../../test/auto-mock'; import { AuthStateService } from '../../auth-state/auth-state.service'; import { LoggerService } from '../../logging/logger.service'; import { StoragePersistenceService } from '../../storage/storage-persistence.service'; @@ -38,21 +38,12 @@ describe('HistoryJwtKeysCallbackHandlerService', () => { TestBed.configureTestingModule({ providers: [ HistoryJwtKeysCallbackHandlerService, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - { provide: AuthStateService, useClass: mockClass(AuthStateService) }, - { provide: FlowsDataService, useClass: mockClass(FlowsDataService) }, - { - provide: SigninKeyDataService, - useClass: mockClass(SigninKeyDataService), - }, - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, - { - provide: ResetAuthDataService, - useClass: mockClass(ResetAuthDataService), - }, + mockProvider(LoggerService), + mockProvider(AuthStateService), + mockProvider(FlowsDataService), + mockProvider(SigninKeyDataService), + mockProvider(StoragePersistenceService), + mockProvider(ResetAuthDataService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/implicit-flow-callback-handler.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/implicit-flow-callback-handler.service.spec.ts index 4e58e949..4f1ec1db 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/implicit-flow-callback-handler.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/implicit-flow-callback-handler.service.spec.ts @@ -1,6 +1,6 @@ import { DOCUMENT } from '@angular/common'; import { TestBed, waitForAsync } from '@angular/core/testing'; -import { mockClass } from '../../../test/auto-mock'; +import { mockProvider } from '../../../test/auto-mock'; import { LoggerService } from '../../logging/logger.service'; import { CallbackContext } from '../callback-context'; import { FlowsDataService } from '../flows-data.service'; @@ -16,12 +16,9 @@ describe('ImplicitFlowCallbackHandlerService', () => { TestBed.configureTestingModule({ providers: [ ImplicitFlowCallbackHandlerService, - { - provide: ResetAuthDataService, - useClass: mockClass(ResetAuthDataService), - }, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - { provide: FlowsDataService, useClass: mockClass(FlowsDataService) }, + mockProvider(FlowsDataService), + mockProvider(ResetAuthDataService), + mockProvider(LoggerService), { provide: DOCUMENT, useValue: { diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-session-callback-handler.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-session-callback-handler.service.spec.ts index 5f01cb51..9973dc3e 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-session-callback-handler.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-session-callback-handler.service.spec.ts @@ -1,5 +1,5 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; -import { mockClass } from '../../../test/auto-mock'; +import { mockProvider } from '../../../test/auto-mock'; import { AuthStateService } from '../../auth-state/auth-state.service'; import { LoggerService } from '../../logging/logger.service'; import { CallbackContext } from '../callback-context'; @@ -15,9 +15,9 @@ describe('RefreshSessionCallbackHandlerService', () => { TestBed.configureTestingModule({ providers: [ RefreshSessionCallbackHandlerService, - { provide: AuthStateService, useClass: mockClass(AuthStateService) }, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - { provide: FlowsDataService, useClass: mockClass(FlowsDataService) }, + mockProvider(AuthStateService), + mockProvider(LoggerService), + mockProvider(FlowsDataService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-token-callback-handler.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-token-callback-handler.service.spec.ts index d0acc21c..ee421b33 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-token-callback-handler.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/refresh-token-callback-handler.service.spec.ts @@ -1,7 +1,7 @@ import { HttpErrorResponse, HttpHeaders } from '@angular/common/http'; import { TestBed, waitForAsync } from '@angular/core/testing'; import { of, throwError } from 'rxjs'; -import { mockClass } from '../../../test/auto-mock'; +import { mockProvider } from '../../../test/auto-mock'; import { createRetriableStream } from '../../../test/create-retriable-stream.helper'; import { DataService } from '../../api/data.service'; import { LoggerService } from '../../logging/logger.service'; @@ -19,13 +19,10 @@ describe('RefreshTokenCallbackHandlerService', () => { TestBed.configureTestingModule({ providers: [ RefreshTokenCallbackHandlerService, - { provide: UrlService, useClass: mockClass(UrlService) }, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - { provide: DataService, useClass: mockClass(DataService) }, - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, + mockProvider(UrlService), + mockProvider(LoggerService), + mockProvider(DataService), + mockProvider(StoragePersistenceService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/state-validation-callback-handler.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/state-validation-callback-handler.service.spec.ts index df0d7f75..eb09a14c 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/state-validation-callback-handler.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/state-validation-callback-handler.service.spec.ts @@ -1,7 +1,7 @@ import { DOCUMENT } from '@angular/common'; import { TestBed, waitForAsync } from '@angular/core/testing'; import { of } from 'rxjs'; -import { mockClass } from '../../../test/auto-mock'; +import { mockProvider } from '../../../test/auto-mock'; import { AuthStateService } from '../../auth-state/auth-state.service'; import { LoggerService } from '../../logging/logger.service'; import { StateValidationResult } from '../../validation/state-validation-result'; @@ -22,16 +22,10 @@ describe('StateValidationCallbackHandlerService', () => { TestBed.configureTestingModule({ providers: [ StateValidationCallbackHandlerService, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - { - provide: StateValidationService, - useClass: mockClass(StateValidationService), - }, - { provide: AuthStateService, useClass: mockClass(AuthStateService) }, - { - provide: ResetAuthDataService, - useClass: mockClass(ResetAuthDataService), - }, + mockProvider(LoggerService), + mockProvider(StateValidationService), + mockProvider(AuthStateService), + mockProvider(ResetAuthDataService), { provide: DOCUMENT, useValue: { diff --git a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/user-callback-handler.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/user-callback-handler.service.spec.ts index 8e452426..5696a6c9 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/user-callback-handler.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/callback-handling/user-callback-handler.service.spec.ts @@ -1,6 +1,6 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { of } from 'rxjs'; -import { mockClass } from '../../../test/auto-mock'; +import { mockProvider } from '../../../test/auto-mock'; import { AuthStateService } from '../../auth-state/auth-state.service'; import { LoggerService } from '../../logging/logger.service'; import { UserService } from '../../user-data/user.service'; @@ -22,14 +22,11 @@ describe('UserCallbackHandlerService', () => { TestBed.configureTestingModule({ providers: [ UserCallbackHandlerService, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - { provide: AuthStateService, useClass: mockClass(AuthStateService) }, - { provide: FlowsDataService, useClass: mockClass(FlowsDataService) }, - { provide: UserService, useClass: mockClass(UserService) }, - { - provide: ResetAuthDataService, - useClass: mockClass(ResetAuthDataService), - }, + mockProvider(LoggerService), + mockProvider(AuthStateService), + mockProvider(FlowsDataService), + mockProvider(UserService), + mockProvider(ResetAuthDataService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/flows/flows-data.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/flows-data.service.spec.ts index 353ef9ff..dc8e2586 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/flows-data.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/flows-data.service.spec.ts @@ -1,5 +1,5 @@ import { TestBed } from '@angular/core/testing'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { LoggerService } from '../logging/logger.service'; import { StoragePersistenceService } from '../storage/storage-persistence.service'; import { CryptoService } from '../utils/crypto/crypto.service'; @@ -16,11 +16,8 @@ describe('Flows Data Service', () => { FlowsDataService, RandomService, CryptoService, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, + mockProvider(LoggerService), + mockProvider(StoragePersistenceService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/flows/random/random.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/random/random.service.spec.ts index fd004fba..44f6aa6a 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/random/random.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/random/random.service.spec.ts @@ -1,5 +1,5 @@ import { TestBed } from '@angular/core/testing'; -import { mockClass } from '../../../test/auto-mock'; +import { mockProvider } from '../../../test/auto-mock'; import { LoggerService } from '../../logging/logger.service'; import { CryptoService } from '../../utils/crypto/crypto.service'; import { RandomService } from './random.service'; @@ -9,11 +9,7 @@ describe('RandomService Tests', () => { beforeEach(() => { TestBed.configureTestingModule({ - providers: [ - RandomService, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - CryptoService, - ], + providers: [RandomService, mockProvider(LoggerService), CryptoService], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/flows/reset-auth-data.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/reset-auth-data.service.spec.ts index c62b5a99..b19b2cfb 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/reset-auth-data.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/reset-auth-data.service.spec.ts @@ -1,5 +1,5 @@ import { TestBed } from '@angular/core/testing'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { AuthStateService } from '../auth-state/auth-state.service'; import { LoggerService } from '../logging/logger.service'; import { UserService } from '../user-data/user.service'; @@ -16,10 +16,10 @@ describe('ResetAuthDataService', () => { TestBed.configureTestingModule({ providers: [ ResetAuthDataService, - { provide: AuthStateService, useClass: mockClass(AuthStateService) }, - { provide: FlowsDataService, useClass: mockClass(FlowsDataService) }, - { provide: UserService, useClass: mockClass(UserService) }, - { provide: LoggerService, useClass: mockClass(LoggerService) }, + mockProvider(AuthStateService), + mockProvider(FlowsDataService), + mockProvider(UserService), + mockProvider(LoggerService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/flows/signin-key-data.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/flows/signin-key-data.service.spec.ts index edc8acc9..08fb0f4c 100644 --- a/projects/angular-auth-oidc-client/src/lib/flows/signin-key-data.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/flows/signin-key-data.service.spec.ts @@ -1,7 +1,7 @@ import { HttpResponse } from '@angular/common/http'; import { TestBed, waitForAsync } from '@angular/core/testing'; import { isObservable, of, throwError } from 'rxjs'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { createRetriableStream } from '../../test/create-retriable-stream.helper'; import { DataService } from '../api/data.service'; import { LoggerService } from '../logging/logger.service'; @@ -34,12 +34,9 @@ describe('Signin Key Data Service', () => { TestBed.configureTestingModule({ providers: [ SigninKeyDataService, - { provide: DataService, useClass: mockClass(DataService) }, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, + mockProvider(DataService), + mockProvider(LoggerService), + mockProvider(StoragePersistenceService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/iframe/check-session.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/iframe/check-session.service.spec.ts index 884f48dc..ac7c8784 100644 --- a/projects/angular-auth-oidc-client/src/lib/iframe/check-session.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/iframe/check-session.service.spec.ts @@ -1,7 +1,7 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { of } from 'rxjs'; import { skip } from 'rxjs/operators'; -import { mockClass } from '../../test/auto-mock'; +import { mockClass, mockProvider } from '../../test/auto-mock'; import { LoggerService } from '../logging/logger.service'; import { OidcSecurityService } from '../oidc.security.service'; import { PublicEventsService } from '../public-events/public-events.service'; @@ -25,16 +25,13 @@ describe('CheckSessionService', () => { OidcSecurityService, IFrameService, PublicEventsService, - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, - { provide: LoggerService, useClass: mockClass(LoggerService) }, + mockProvider(StoragePersistenceService), + mockProvider(LoggerService), + mockProvider(PlatformProvider), { provide: AbstractSecurityStorage, useClass: mockClass(DefaultSessionStorageService), }, - { provide: PlatformProvider, useClass: mockClass(PlatformProvider) }, ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/iframe/refresh-session-iframe.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/iframe/refresh-session-iframe.service.spec.ts index a667ddac..1dd2fcaf 100644 --- a/projects/angular-auth-oidc-client/src/lib/iframe/refresh-session-iframe.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/iframe/refresh-session-iframe.service.spec.ts @@ -1,6 +1,6 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { of } from 'rxjs'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { LoggerService } from '../logging/logger.service'; import { UrlService } from '../utils/url/url.service'; import { RefreshSessionIframeService } from './refresh-session-iframe.service'; @@ -14,12 +14,9 @@ describe('RefreshSessionIframeService ', () => { TestBed.configureTestingModule({ providers: [ RefreshSessionIframeService, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - { provide: UrlService, useClass: mockClass(UrlService) }, - { - provide: SilentRenewService, - useClass: mockClass(SilentRenewService), - }, + mockProvider(SilentRenewService), + mockProvider(LoggerService), + mockProvider(UrlService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.spec.ts index 9987db37..36c088c4 100644 --- a/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.spec.ts @@ -1,6 +1,6 @@ import { fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { Observable, of, throwError } from 'rxjs'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { AuthStateService } from '../auth-state/auth-state.service'; import { ImplicitFlowCallbackService } from '../callback/implicit-flow-callback.service'; import { IntervalService } from '../callback/interval.service'; @@ -31,19 +31,13 @@ describe('SilentRenewService ', () => { providers: [ SilentRenewService, IFrameService, - { provide: FlowsService, useClass: mockClass(FlowsService) }, - { - provide: ResetAuthDataService, - useClass: mockClass(ResetAuthDataService), - }, - { provide: FlowsDataService, useClass: mockClass(FlowsDataService) }, - { provide: AuthStateService, useClass: mockClass(AuthStateService) }, - { provide: LoggerService, useClass: mockClass(LoggerService) }, + mockProvider(FlowsService), + mockProvider(ResetAuthDataService), + mockProvider(FlowsDataService), + mockProvider(AuthStateService), + mockProvider(LoggerService), + mockProvider(ImplicitFlowCallbackService), FlowHelper, - { - provide: ImplicitFlowCallbackService, - useClass: mockClass(ImplicitFlowCallbackService), - }, IntervalService, ], }); diff --git a/projects/angular-auth-oidc-client/src/lib/interceptor/auth.interceptor.spec.ts b/projects/angular-auth-oidc-client/src/lib/interceptor/auth.interceptor.spec.ts index c047155d..8ed0f6a7 100644 --- a/projects/angular-auth-oidc-client/src/lib/interceptor/auth.interceptor.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/interceptor/auth.interceptor.spec.ts @@ -10,7 +10,7 @@ import { provideHttpClientTesting, } from '@angular/common/http/testing'; import { TestBed, waitForAsync } from '@angular/core/testing'; -import { mockClass, mockProvider } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { AuthStateService } from '../auth-state/auth-state.service'; import { ConfigurationService } from '../config/config.service'; import { LoggerService } from '../logging/logger.service'; @@ -35,11 +35,8 @@ describe(`AuthHttpInterceptor`, () => { useClass: AuthInterceptor, multi: true, }, - { provide: AuthStateService, useClass: mockClass(AuthStateService) }, - { - provide: LoggerService, - useClass: mockClass(LoggerService), - }, + mockProvider(AuthStateService), + mockProvider(LoggerService), mockProvider(ConfigurationService), ], }); @@ -65,11 +62,8 @@ describe(`AuthHttpInterceptor`, () => { ClosestMatchingRouteService, provideHttpClient(withInterceptors([authInterceptor()])), provideHttpClientTesting(), - { provide: AuthStateService, useClass: mockClass(AuthStateService) }, - { - provide: LoggerService, - useClass: mockClass(LoggerService), - }, + mockProvider(AuthStateService), + mockProvider(LoggerService), mockProvider(ConfigurationService), ], }); diff --git a/projects/angular-auth-oidc-client/src/lib/interceptor/closest-matching-route.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/interceptor/closest-matching-route.service.spec.ts index ccc62290..7cf55816 100644 --- a/projects/angular-auth-oidc-client/src/lib/interceptor/closest-matching-route.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/interceptor/closest-matching-route.service.spec.ts @@ -1,5 +1,5 @@ import { TestBed } from '@angular/core/testing'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { LoggerService } from '../logging/logger.service'; import { ClosestMatchingRouteService } from './closest-matching-route.service'; @@ -8,13 +8,7 @@ describe('ClosestMatchingRouteService', () => { beforeEach(() => { TestBed.configureTestingModule({ - providers: [ - ClosestMatchingRouteService, - { - provide: LoggerService, - useClass: mockClass(LoggerService), - }, - ], + providers: [ClosestMatchingRouteService, mockProvider(LoggerService)], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/login/login.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/login.service.spec.ts index 7351ea96..bf538bda 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/login.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/login.service.spec.ts @@ -1,7 +1,7 @@ import { CommonModule } from '@angular/common'; import { TestBed, waitForAsync } from '@angular/core/testing'; import { of } from 'rxjs'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { StoragePersistenceService } from '../storage/storage-persistence.service'; import { LoginResponse } from './login-response'; import { LoginService } from './login.service'; @@ -23,17 +23,11 @@ describe('LoginService', () => { imports: [CommonModule], providers: [ LoginService, - { provide: ParLoginService, useClass: mockClass(ParLoginService) }, - { provide: PopUpLoginService, useClass: mockClass(PopUpLoginService) }, - { - provide: StandardLoginService, - useClass: mockClass(StandardLoginService), - }, - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, - { provide: PopUpService, useClass: mockClass(PopUpService) }, + mockProvider(ParLoginService), + mockProvider(PopUpLoginService), + mockProvider(StandardLoginService), + mockProvider(StoragePersistenceService), + mockProvider(PopUpService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/login/par/par.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/par/par.service.spec.ts index 98dd29fe..7a222d7f 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/par/par.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/par/par.service.spec.ts @@ -1,7 +1,7 @@ import { HttpHeaders } from '@angular/common/http'; import { TestBed, waitForAsync } from '@angular/core/testing'; import { of, throwError } from 'rxjs'; -import { mockClass } from '../../../test/auto-mock'; +import { mockProvider } from '../../../test/auto-mock'; import { createRetriableStream } from '../../../test/create-retriable-stream.helper'; import { DataService } from '../../api/data.service'; import { LoggerService } from '../../logging/logger.service'; @@ -19,23 +19,10 @@ describe('ParService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ - ParService, - { - provide: LoggerService, - useClass: mockClass(LoggerService), - }, - { - provide: UrlService, - useClass: mockClass(UrlService), - }, - { - provide: DataService, - useClass: mockClass(DataService), - }, - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, + mockProvider(LoggerService), + mockProvider(UrlService), + mockProvider(DataService), + mockProvider(StoragePersistenceService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts index d5fd7b8a..27d714e1 100644 --- a/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/login/popup/popup.service.spec.ts @@ -1,5 +1,5 @@ import { fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; -import { mockClass } from '../../../test/auto-mock'; +import { mockProvider } from '../../../test/auto-mock'; import { OpenIdConfiguration } from '../../config/openid-configuration'; import { LoggerService } from '../../logging/logger.service'; import { StoragePersistenceService } from '../../storage/storage-persistence.service'; @@ -14,12 +14,8 @@ describe('PopUpService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - PopUpService, + mockProvider(StoragePersistenceService), + mockProvider(LoggerService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/logoff-revoke/logoff-revocation.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/logoff-revoke/logoff-revocation.service.spec.ts index 0428da7c..94d62992 100644 --- a/projects/angular-auth-oidc-client/src/lib/logoff-revoke/logoff-revocation.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/logoff-revoke/logoff-revocation.service.spec.ts @@ -1,7 +1,7 @@ import { HttpHeaders } from '@angular/common/http'; import { TestBed, waitForAsync } from '@angular/core/testing'; import { Observable, of, throwError } from 'rxjs'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { createRetriableStream } from '../../test/create-retriable-stream.helper'; import { DataService } from '../api/data.service'; import { ResetAuthDataService } from '../flows/reset-auth-data.service'; @@ -25,23 +25,13 @@ describe('Logout and Revoke Service', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ - LogoffRevocationService, - { provide: DataService, useClass: mockClass(DataService) }, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, - { provide: UrlService, useClass: mockClass(UrlService) }, - { - provide: CheckSessionService, - useClass: mockClass(CheckSessionService), - }, - { - provide: ResetAuthDataService, - useClass: mockClass(ResetAuthDataService), - }, - { provide: RedirectService, useClass: mockClass(RedirectService) }, + mockProvider(DataService), + mockProvider(LoggerService), + mockProvider(StoragePersistenceService), + mockProvider(UrlService), + mockProvider(CheckSessionService), + mockProvider(ResetAuthDataService), + mockProvider(RedirectService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.spec.ts index 250cb2ed..33142712 100644 --- a/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/validation/state-validation.service.spec.ts @@ -1,6 +1,6 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { of } from 'rxjs'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { AuthWellKnownEndpoints } from '../config/auth-well-known/auth-well-known-endpoints'; import { OpenIdConfiguration } from '../config/openid-configuration'; import { CallbackContext } from '../flows/callback-context'; @@ -26,21 +26,10 @@ describe('State Validation Service', () => { beforeEach(() => { TestBed.configureTestingModule({ - imports: [], providers: [ - StateValidationService, - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, - { - provide: TokenValidationService, - useClass: mockClass(TokenValidationService), - }, - { - provide: LoggerService, - useClass: mockClass(LoggerService), - }, + mockProvider(StoragePersistenceService), + mockProvider(TokenValidationService), + mockProvider(LoggerService), TokenHelperService, EqualityService, FlowHelper, From e22aee67b5cf1b29cd00bafcf95f186fddda2fde Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Mon, 18 Mar 2024 20:27:57 +0100 Subject: [PATCH 51/56] Refactor test dependencies --- .../src/lib/auth-state/check-auth.service.spec.ts | 8 ++------ .../src/lib/config/config.service.spec.ts | 7 ++----- .../src/lib/iframe/check-session.service.spec.ts | 10 +++++----- .../lib/storage/browser-storage.service.spec.ts | 7 +++---- .../storage/storage-persistence.service.spec.ts | 10 ++-------- .../src/lib/user-data/user-service.spec.ts | 14 +++++--------- .../utils/tokenHelper/token-helper.service.spec.ts | 7 ++----- .../angular-auth-oidc-client/src/test/auto-mock.ts | 13 ++++++++++++- 8 files changed, 33 insertions(+), 43 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts index a4de0cb0..df28d48c 100644 --- a/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/auth-state/check-auth.service.spec.ts @@ -1,7 +1,7 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { of, throwError } from 'rxjs'; -import { mockClass, mockProvider } from '../../test/auto-mock'; +import { mockAbstractProvider, mockProvider } from '../../test/auto-mock'; import { AutoLoginService } from '../auto-login/auto-login.service'; import { CallbackService } from '../callback/callback.service'; import { PeriodicallyTokenCheckService } from '../callback/periodically-token-check.service'; @@ -55,12 +55,8 @@ describe('CheckAuthService', () => { mockProvider(PopUpService), mockProvider(CurrentUrlService), mockProvider(PublicEventsService), - { - provide: StsConfigLoader, - useClass: mockClass(StsConfigStaticLoader), - }, + mockAbstractProvider(StsConfigLoader, StsConfigStaticLoader), AutoLoginService, - CheckAuthService, mockProvider(StoragePersistenceService), ], }); diff --git a/projects/angular-auth-oidc-client/src/lib/config/config.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/config/config.service.spec.ts index c06585a0..fe7ba74e 100644 --- a/projects/angular-auth-oidc-client/src/lib/config/config.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/config/config.service.spec.ts @@ -1,6 +1,6 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { of } from 'rxjs'; -import { mockClass, mockProvider } from '../../test/auto-mock'; +import { mockAbstractProvider, mockProvider } from '../../test/auto-mock'; import { LoggerService } from '../logging/logger.service'; import { EventTypes } from '../public-events/event-types'; import { PublicEventsService } from '../public-events/public-events.service'; @@ -31,10 +31,7 @@ describe('Configuration Service', () => { ConfigValidationService, mockProvider(PlatformProvider), mockProvider(AuthWellKnownService), - { - provide: StsConfigLoader, - useClass: mockClass(StsConfigStaticLoader), - }, + mockAbstractProvider(StsConfigLoader, StsConfigStaticLoader), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/iframe/check-session.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/iframe/check-session.service.spec.ts index ac7c8784..db4db75b 100644 --- a/projects/angular-auth-oidc-client/src/lib/iframe/check-session.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/iframe/check-session.service.spec.ts @@ -1,7 +1,7 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { of } from 'rxjs'; import { skip } from 'rxjs/operators'; -import { mockClass, mockProvider } from '../../test/auto-mock'; +import { mockAbstractProvider, mockProvider } from '../../test/auto-mock'; import { LoggerService } from '../logging/logger.service'; import { OidcSecurityService } from '../oidc.security.service'; import { PublicEventsService } from '../public-events/public-events.service'; @@ -28,10 +28,10 @@ describe('CheckSessionService', () => { mockProvider(StoragePersistenceService), mockProvider(LoggerService), mockProvider(PlatformProvider), - { - provide: AbstractSecurityStorage, - useClass: mockClass(DefaultSessionStorageService), - }, + mockAbstractProvider( + AbstractSecurityStorage, + DefaultSessionStorageService + ), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/storage/browser-storage.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/storage/browser-storage.service.spec.ts index c4cfe98c..e40c86e2 100644 --- a/projects/angular-auth-oidc-client/src/lib/storage/browser-storage.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/storage/browser-storage.service.spec.ts @@ -1,23 +1,22 @@ import { TestBed } from '@angular/core/testing'; -import { mockClass } from '../../test/auto-mock'; +import { mockClass, mockProvider } from '../../test/auto-mock'; import { LoggerService } from '../logging/logger.service'; import { AbstractSecurityStorage } from './abstract-security-storage'; import { BrowserStorageService } from './browser-storage.service'; import { DefaultSessionStorageService } from './default-sessionstorage.service'; -describe('Browser Service', () => { +describe('BrowserStorageService', () => { let service: BrowserStorageService; let abstractSecurityStorage: AbstractSecurityStorage; beforeEach(() => { TestBed.configureTestingModule({ providers: [ + mockProvider(LoggerService), { provide: AbstractSecurityStorage, useClass: mockClass(DefaultSessionStorageService), }, - BrowserStorageService, - { provide: LoggerService, useClass: mockClass(LoggerService) }, ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/storage/storage-persistence.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/storage/storage-persistence.service.spec.ts index 9cf90aa8..204fee1a 100644 --- a/projects/angular-auth-oidc-client/src/lib/storage/storage-persistence.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/storage/storage-persistence.service.spec.ts @@ -1,5 +1,5 @@ import { TestBed } from '@angular/core/testing'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { BrowserStorageService } from './browser-storage.service'; import { StoragePersistenceService } from './storage-persistence.service'; @@ -9,13 +9,7 @@ describe('Storage Persistence Service', () => { beforeEach(() => { TestBed.configureTestingModule({ - providers: [ - StoragePersistenceService, - { - provide: BrowserStorageService, - useClass: mockClass(BrowserStorageService), - }, - ], + providers: [mockProvider(BrowserStorageService)], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/user-data/user-service.spec.ts b/projects/angular-auth-oidc-client/src/lib/user-data/user-service.spec.ts index 830d350f..1ff7a2ec 100644 --- a/projects/angular-auth-oidc-client/src/lib/user-data/user-service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/user-data/user-service.spec.ts @@ -1,6 +1,6 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { Observable, of, throwError } from 'rxjs'; -import { mockClass } from '../../test/auto-mock'; +import { mockProvider } from '../../test/auto-mock'; import { createRetriableStream } from '../../test/create-retriable-stream.helper'; import { DataService } from '../api/data.service'; import { OpenIdConfiguration } from '../config/openid-configuration'; @@ -29,16 +29,12 @@ describe('User Service', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ - { - provide: StoragePersistenceService, - useClass: mockClass(StoragePersistenceService), - }, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - { provide: DataService, useClass: mockClass(DataService) }, - { provide: PlatformProvider, useClass: mockClass(PlatformProvider) }, + mockProvider(StoragePersistenceService), + mockProvider(LoggerService), + mockProvider(DataService), + mockProvider(PlatformProvider), PublicEventsService, TokenHelperService, - UserService, FlowHelper, ], }); diff --git a/projects/angular-auth-oidc-client/src/lib/utils/tokenHelper/token-helper.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/utils/tokenHelper/token-helper.service.spec.ts index 8dc3ce58..d3ee296d 100644 --- a/projects/angular-auth-oidc-client/src/lib/utils/tokenHelper/token-helper.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/utils/tokenHelper/token-helper.service.spec.ts @@ -1,5 +1,5 @@ import { TestBed } from '@angular/core/testing'; -import { mockClass } from '../../../test/auto-mock'; +import { mockProvider } from '../../../test/auto-mock'; import { LoggerService } from '../../logging/logger.service'; import { TokenHelperService } from './token-helper.service'; @@ -8,10 +8,7 @@ describe('Token Helper Service', () => { beforeEach(() => { TestBed.configureTestingModule({ - providers: [ - TokenHelperService, - { provide: LoggerService, useClass: mockClass(LoggerService) }, - ], + providers: [mockProvider(LoggerService)], }); }); diff --git a/projects/angular-auth-oidc-client/src/test/auto-mock.ts b/projects/angular-auth-oidc-client/src/test/auto-mock.ts index 78c3a164..5cc7cbb5 100644 --- a/projects/angular-auth-oidc-client/src/test/auto-mock.ts +++ b/projects/angular-auth-oidc-client/src/test/auto-mock.ts @@ -1,3 +1,5 @@ +import { Provider } from '@angular/core'; + export function mockClass(obj: new (...args: any[]) => T): any { const keys = Object.getOwnPropertyNames(obj.prototype); const allMethods = keys.filter((key) => { @@ -30,9 +32,18 @@ export function mockClass(obj: new (...args: any[]) => T): any { return mockedClass; } -export function mockProvider(obj: new (...args: any[]) => T): any { +export function mockProvider(obj: new (...args: any[]) => T): Provider { return { provide: obj, useClass: mockClass(obj), }; } + +export function mockAbstractProvider( + type: abstract new (...args: any[]) => T, + mockType: new (...args: any[]) => M +): Provider { + const mock = mockClass(mockType); + + return { provide: type, useClass: mock }; +} From f65cad2f538b5e5a288e8f0b5b827c9390ba3659 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Mon, 18 Mar 2024 20:36:52 +0100 Subject: [PATCH 52/56] Fix dependency injection issue in data and http base services --- projects/angular-auth-oidc-client/src/lib/api/data.service.ts | 4 ++-- .../angular-auth-oidc-client/src/lib/api/http-base.service.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/api/data.service.ts b/projects/angular-auth-oidc-client/src/lib/api/data.service.ts index 097e7dfe..31a93b91 100644 --- a/projects/angular-auth-oidc-client/src/lib/api/data.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/api/data.service.ts @@ -1,5 +1,5 @@ import { HttpHeaders, HttpParams } from '@angular/common/http'; -import { Injectable } from '@angular/core'; +import { Injectable, inject } from '@angular/core'; import { Observable } from 'rxjs'; import { OpenIdConfiguration } from '../config/openid-configuration'; import { HttpBaseService } from './http-base.service'; @@ -8,7 +8,7 @@ const NGSW_CUSTOM_PARAM = 'ngsw-bypass'; @Injectable({ providedIn: 'root' }) export class DataService { - constructor(private readonly httpClient: HttpBaseService) {} + private readonly httpClient = inject(HttpBaseService); get( url: string, diff --git a/projects/angular-auth-oidc-client/src/lib/api/http-base.service.ts b/projects/angular-auth-oidc-client/src/lib/api/http-base.service.ts index 77dc4382..5116101d 100644 --- a/projects/angular-auth-oidc-client/src/lib/api/http-base.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/api/http-base.service.ts @@ -1,10 +1,10 @@ import { HttpClient } from '@angular/common/http'; -import { Injectable } from '@angular/core'; +import { Injectable, inject } from '@angular/core'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class HttpBaseService { - constructor(private readonly http: HttpClient) {} + private readonly http = inject(HttpClient); get(url: string, params?: { [key: string]: any }): Observable { return this.http.get(url, params); From b3a50895c289d190c78a49adc6713add690aec95 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Mon, 18 Mar 2024 20:49:18 +0100 Subject: [PATCH 53/56] Update stsCallback$ return type to Observable --- .../src/lib/callback/callback.service.ts | 2 +- .../angular-auth-oidc-client/src/lib/oidc.security.service.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/callback/callback.service.ts b/projects/angular-auth-oidc-client/src/lib/callback/callback.service.ts index 4d1fd1e1..5f90d7b8 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/callback.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/callback.service.ts @@ -12,7 +12,7 @@ import { ImplicitFlowCallbackService } from './implicit-flow-callback.service'; export class CallbackService { private readonly stsCallbackInternal$ = new Subject(); - get stsCallback$(): Observable { + get stsCallback$(): Observable { return this.stsCallbackInternal$.asObservable(); } diff --git a/projects/angular-auth-oidc-client/src/lib/oidc.security.service.ts b/projects/angular-auth-oidc-client/src/lib/oidc.security.service.ts index 28072903..8760fc4c 100644 --- a/projects/angular-auth-oidc-client/src/lib/oidc.security.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/oidc.security.service.ts @@ -59,7 +59,7 @@ export class OidcSecurityService { /** * Emits on a Security Token Service callback. The observable will never contain a value. */ - get stsCallback$(): Observable { + get stsCallback$(): Observable { return this.callbackService.stsCallback$; } From 6b19d33651e8b8931ceb81ba29efe213bcafd380 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Mon, 18 Mar 2024 20:57:03 +0100 Subject: [PATCH 54/56] Fix spy return value in stsCallback$ test --- .../src/lib/oidc.security.service.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/projects/angular-auth-oidc-client/src/lib/oidc.security.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/oidc.security.service.spec.ts index ffadcedb..9385c6dc 100644 --- a/projects/angular-auth-oidc-client/src/lib/oidc.security.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/oidc.security.service.spec.ts @@ -121,7 +121,7 @@ describe('OidcSecurityService', () => { const spy = spyOnProperty( callbackService, 'stsCallback$' - ).and.returnValue(of({ some: 'data' })); + ).and.returnValue(of()); oidcSecurityService.stsCallback$.subscribe(() => { expect(spy).toHaveBeenCalledTimes(1); From f2ceaefdf6c1e949a573e02495a9f4efd4d3eb2e Mon Sep 17 00:00:00 2001 From: Fabian Gosebrink Date: Thu, 21 Mar 2024 11:07:27 +0100 Subject: [PATCH 55/56] Update projects/angular-auth-oidc-client/src/lib/callback/interval.service.ts Co-authored-by: Tim Deschryver <28659384+timdeschryver@users.noreply.github.com> --- .../src/lib/callback/interval.service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/projects/angular-auth-oidc-client/src/lib/callback/interval.service.ts b/projects/angular-auth-oidc-client/src/lib/callback/interval.service.ts index 54c0fa35..696fb88a 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/interval.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/interval.service.ts @@ -22,7 +22,7 @@ export class IntervalService { const millisecondsDelayBetweenTokenCheck = repeatAfterSeconds * 1000; return new Observable((subscriber) => { - let intervalId: NodeJS.Timeout; + let intervalId?: number; this.zone.runOutsideAngular(() => { intervalId = setInterval( From d2da01e81b459bd86f2cb6af629cde381ad5b361 Mon Sep 17 00:00:00 2001 From: FabianGosebrink Date: Thu, 21 Mar 2024 18:31:46 +0100 Subject: [PATCH 56/56] Fix interval service injection and use of setInterval --- .../lib/callback/code-flow-callback.service.spec.ts | 2 +- .../callback/implicit-flow-callback.service.spec.ts | 3 +-- .../src/lib/callback/interval.service.spec.ts | 11 ++++++++++- .../src/lib/callback/interval.service.ts | 12 +++++++----- .../periodically-token-check.service.spec.ts | 10 +++------- .../refresh-session-refresh-token.service.spec.ts | 2 +- .../src/lib/iframe/silent-renew.service.spec.ts | 2 +- 7 files changed, 24 insertions(+), 18 deletions(-) diff --git a/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.spec.ts index 37656c61..3e9996c4 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/code-flow-callback.service.spec.ts @@ -23,7 +23,7 @@ describe('CodeFlowCallbackService ', () => { CodeFlowCallbackService, mockProvider(FlowsService), mockProvider(FlowsDataService), - IntervalService, + mockProvider(IntervalService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/callback/implicit-flow-callback.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/callback/implicit-flow-callback.service.spec.ts index 608d4824..830de5e5 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/implicit-flow-callback.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/implicit-flow-callback.service.spec.ts @@ -20,10 +20,9 @@ describe('ImplicitFlowCallbackService ', () => { TestBed.configureTestingModule({ imports: [RouterTestingModule], providers: [ - ImplicitFlowCallbackService, mockProvider(FlowsService), mockProvider(FlowsDataService), - IntervalService, + mockProvider(IntervalService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/callback/interval.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/callback/interval.service.spec.ts index 6fe238aa..2e124f50 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/interval.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/interval.service.spec.ts @@ -7,7 +7,16 @@ describe('IntervalService', () => { beforeEach(() => { TestBed.configureTestingModule({ - providers: [IntervalService], + providers: [ + { + provide: Document, + useValue: { + defaultView: { + setInterval: window.setInterval, + }, + }, + }, + ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/callback/interval.service.ts b/projects/angular-auth-oidc-client/src/lib/callback/interval.service.ts index 696fb88a..25d963f1 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/interval.service.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/interval.service.ts @@ -1,11 +1,13 @@ -import { Injectable, NgZone } from '@angular/core'; +import { Injectable, NgZone, inject } from '@angular/core'; import { Observable, Subscription } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class IntervalService { - runTokenValidationRunning: Subscription | null = null; + private readonly zone = inject(NgZone); + + private readonly document = inject(Document); - constructor(private readonly zone: NgZone) {} + runTokenValidationRunning: Subscription | null = null; isTokenValidationRunning(): boolean { return Boolean(this.runTokenValidationRunning); @@ -22,10 +24,10 @@ export class IntervalService { const millisecondsDelayBetweenTokenCheck = repeatAfterSeconds * 1000; return new Observable((subscriber) => { - let intervalId?: number; + let intervalId: number | undefined; this.zone.runOutsideAngular(() => { - intervalId = setInterval( + intervalId = this.document?.defaultView?.setInterval( () => this.zone.run(() => subscriber.next()), millisecondsDelayBetweenTokenCheck ); diff --git a/projects/angular-auth-oidc-client/src/lib/callback/periodically-token-check.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/callback/periodically-token-check.service.spec.ts index 6941af51..93e470e2 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/periodically-token-check.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/periodically-token-check.service.spec.ts @@ -43,7 +43,7 @@ describe('PeriodicallyTokenCheckService', () => { mockProvider(AuthStateService), mockProvider(RefreshSessionIframeService), mockProvider(RefreshSessionRefreshTokenService), - IntervalService, + mockProvider(IntervalService), mockProvider(StoragePersistenceService), mockProvider(PublicEventsService), mockProvider(ConfigurationService), @@ -67,6 +67,8 @@ describe('PeriodicallyTokenCheckService', () => { resetAuthDataService = TestBed.inject(ResetAuthDataService); publicEventsService = TestBed.inject(PublicEventsService); configurationService = TestBed.inject(ConfigurationService); + + spyOn(intervalService, 'startPeriodicTokenCheck').and.returnValue(of(null)); }); afterEach(() => { @@ -154,9 +156,6 @@ describe('PeriodicallyTokenCheckService', () => { { silentRenew: true, configId: 'configId1', tokenRefreshInSeconds: 1 }, ]; - spyOn(intervalService, 'startPeriodicTokenCheck').and.returnValue( - of(null) - ); spyOn( periodicallyTokenCheckService as any, 'shouldStartPeriodicallyCheckForConfig' @@ -196,9 +195,6 @@ describe('PeriodicallyTokenCheckService', () => { { silentRenew: true, configId: 'configId1', tokenRefreshInSeconds: 1 }, ]; - spyOn(intervalService, 'startPeriodicTokenCheck').and.returnValue( - of(null) - ); spyOn( periodicallyTokenCheckService as any, 'shouldStartPeriodicallyCheckForConfig' diff --git a/projects/angular-auth-oidc-client/src/lib/callback/refresh-session-refresh-token.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/callback/refresh-session-refresh-token.service.spec.ts index 0b432f2d..6aab19d5 100644 --- a/projects/angular-auth-oidc-client/src/lib/callback/refresh-session-refresh-token.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/callback/refresh-session-refresh-token.service.spec.ts @@ -22,7 +22,7 @@ describe('RefreshSessionRefreshTokenService', () => { mockProvider(LoggerService), mockProvider(FlowsService), mockProvider(ResetAuthDataService), - IntervalService, + mockProvider(IntervalService), ], }); }); diff --git a/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.spec.ts b/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.spec.ts index 36c088c4..da0d92f3 100644 --- a/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.spec.ts +++ b/projects/angular-auth-oidc-client/src/lib/iframe/silent-renew.service.spec.ts @@ -37,8 +37,8 @@ describe('SilentRenewService ', () => { mockProvider(AuthStateService), mockProvider(LoggerService), mockProvider(ImplicitFlowCallbackService), + mockProvider(IntervalService), FlowHelper, - IntervalService, ], }); });