import { Injector } from '@angular/core'; import { Router,UrlSerializer } from '@angular/router'; import { AuthConfig, OAuthService, JwksValidationHandler, OAuthErrorEvent } from 'angular-oauth2-oidc'; import { AppConfig } from "./app.config"; function getAuthConfig(appConfig: AppConfig): AuthConfig { let authConfig: AuthConfig = new AuthConfig(); authConfig.issuer = appConfig.getConfig("issuer"); authConfig.redirectUri = window.location.origin + "/cb"; authConfig.silentRefreshRedirectUri = window.location.origin + "/silent-refresh.html"; authConfig.clientId = appConfig.getConfig("clientId"); authConfig.customQueryParams = { audience: appConfig.getConfig("audience") }; authConfig.scope = "openid profile email"; authConfig.oidc = true; authConfig.disableAtHashCheck = true; authConfig.requireHttps = appConfig.getConfig("requireHttps"); return authConfig; } export function appConfigFactory(injector:Injector, appConfig: AppConfig, oauthService: OAuthService): () => Promise { return (): Promise => { return appConfig.load().then(() => { oauthService.events.subscribe((event) => { console.log(event.type); if (event.type == 'token_error' || event.type == 'silent_refresh_timeout') { let e = event as OAuthErrorEvent; let p = e.params as any; if (event.type == 'silent_refresh_timeout' || (p.error && p.error == 'login_required')) { let router = injector.get(Router); console.log("Session expired"); router.navigate(['loggedout'], { queryParams: { redirectTo: router.url } }); } } }); oauthService.configure(getAuthConfig(appConfig)); oauthService.tokenValidationHandler = new JwksValidationHandler(); oauthService.tokenValidationHandler.validateAtHash = function () { return new Promise((res) => { res(true); }) }; oauthService.setupAutomaticSilentRefresh(); let router = injector.get(Router); var urlTree = router.parseUrl(window.location.href); var urlPath = window.location.pathname; oauthService.loadDiscoveryDocument().then(() => { oauthService.tryLogin({ onTokenReceived: (info) => { urlPath = info.state; } }).then(() => { let router = injector.get(Router); if (!oauthService.hasValidAccessToken()) { oauthService.initImplicitFlow(urlPath); } else { router.navigateByUrl(urlPath); } }); }) }); } }