angular-oauth2-oidc-codeflow-pkce
Version:
[](https://travis-ci.org/bechhansen/angular-oauth2-oidc)
3 lines (2 loc) • 39.9 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@angular/core"),require("@angular/common/http"),require("rxjs"),require("rxjs/operators"),require("@angular/common"),require("jsrsasign")):"function"==typeof define&&define.amd?define("angular-oauth2-oidc-codeflow-pkce",["exports","@angular/core","@angular/common/http","rxjs","rxjs/operators","@angular/common","jsrsasign"],t):t(e["angular-oauth2-oidc-codeflow-pkce"]={},e.ng.core,e.ng.common.http,e.rxjs,e.Rx.Observable.prototype,e.ng.common,e.jsrsasign)}(this,function(e,t,f,h,l,n,d){"use strict";var o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])};function s(e,t){function n(){this.constructor=e}o(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function S(e){var t="function"==typeof Symbol&&e[Symbol.iterator],n=0;return t?t.call(e):{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}}function r(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var o,r,s=n.call(e),i=[];try{for(;(void 0===t||0<t--)&&!(o=s.next()).done;)i.push(o.value)}catch(c){r={error:c}}finally{try{o&&!o.done&&(n=s["return"])&&n.call(s)}finally{if(r)throw r.error}}return i}var i=function(){this.preventClearHashAfterLogin=!1},c=function(){},a=function(){},u=function(){},p=function(){function e(){}return e.prototype.validateAtHash=function(e){var t=this.inferHashAlgorithm(e.idTokenHeader),n=this.calcHash(e.accessToken,t),o=n.substr(0,n.length/2),r=btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),s=e.idTokenClaims.at_hash.replace(/=/g,"");return r!==s&&(console.error("exptected at_hash: "+r),console.error("actual at_hash: "+s)),r===s},e.prototype.inferHashAlgorithm=function(e){var t=e.alg;if(!t.match(/^.S[0-9]{3}$/))throw new Error("Algorithm not supported: "+t);return"sha"+t.substr(2)},e}(),m=function(){function e(){}return e.prototype.getHashFragmentParams=function(e){var t=e||window.location.hash;if(0!==(t=decodeURIComponent(t)).indexOf("#"))return{};var n=t.indexOf("?");return t=-1<n?t.substr(n+1):t.substr(1),this.parseQueryString(t)},e.prototype.parseQueryString=function(e){var t,n,o,r,s,i,c,a={};if(null===e)return a;t=e.split("&");for(var u=0;u<t.length;u++)-1===(o=(n=t[u]).indexOf("="))?(r=n,s=null):(r=n.substr(0,o),s=n.substr(o+1)),i=decodeURIComponent(r),c=decodeURIComponent(s),"/"===i.substr(0,1)&&(i=i.substr(1)),a[i]=c;return a},e}();m.decorators=[{type:t.Injectable}];var g=function(e){this.type=e},v=function(o){function e(e,t){void 0===t&&(t=null);var n=o.call(this,e)||this;return n.info=t,n}return s(e,o),e}(g),k=function(o){function e(e,t){void 0===t&&(t=null);var n=o.call(this,e)||this;return n.info=t,n}return s(e,o),e}(g),y=function(r){function e(e,t,n){void 0===n&&(n=null);var o=r.call(this,e)||this;return o.reason=t,o.params=n,o}return s(e,r),e}(g);function _(e){var t=e.replace(/\-/g,"+").replace(/\_/g,"/");return decodeURIComponent(atob(t).split("").map(function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}var w=function(e){this.clientId="",this.redirectUri="",this.postLogoutRedirectUri="",this.loginUrl="",this.scope="openid profile",this.resource="",this.rngUrl="",this.oidc=!0,this.requestAccessToken=!0,this.options=null,this.issuer="",this.logoutUrl="",this.clearHashAfterLogin=!0,this.tokenEndpoint=null,this.customUserinfoEndpoint=null,this.userinfoEndpoint=null,this.responseType="token",this.showDebugInformation=!1,this.silentRefreshRedirectUri="",this.silentRefreshMessagePrefix="",this.silentRefreshShowIFrame=!1,this.siletRefreshTimeout=2e4,this.silentRefreshTimeout=2e4,this.dummyClientSecret=null,this.requireHttps="remoteOnly",this.strictDiscoveryDocumentValidation=!0,this.jwks=null,this.customQueryParams=null,this.silentRefreshIFrameName="angular-oauth-oidc-silent-refresh-iframe",this.timeoutFactor=.75,this.sessionChecksEnabled=!1,this.sessionCheckIntervall=3e3,this.sessionCheckIFrameUrl=null,this.sessionCheckIFrameName="angular-oauth-oidc-check-session-iframe",this.disableAtHashCheck=!1,this.skipSubjectCheck=!1,this.useIdTokenHintForSilentRefresh=!1,this.skipIssuerCheck=!1,this.nonceStateSeparator=";",this.useHttpBasicAuthForPasswordFlow=!1,this.disableNonceCheck=!1,this.openUri=function(e){location.href=e},e&&Object.assign(this,e)},b=function(){function e(){}return e.prototype.encodeKey=function(e){return encodeURIComponent(e)},e.prototype.encodeValue=function(e){return encodeURIComponent(e)},e.prototype.decodeKey=function(e){return decodeURIComponent(e)},e.prototype.decodeValue=function(e){return decodeURIComponent(e)},e}(),T=function(a){function e(e,t,n,o,r,s){var i=a.call(this)||this;i.ngZone=e,i.http=t,i.config=r,i.urlHelper=s,i.discoveryDocumentLoaded=!1,i.state="",i.eventsSubject=new h.Subject,i.discoveryDocumentLoadedSubject=new h.Subject,i.grantTypesSupported=[],i.inImplicitFlow=!1,i.discoveryDocumentLoaded$=i.discoveryDocumentLoadedSubject.asObservable(),i.events=i.eventsSubject.asObservable(),o&&(i.tokenValidationHandler=o),r&&i.configure(r);try{n?i.setStorage(n):"undefined"!=typeof sessionStorage&&i.setStorage(sessionStorage)}catch(c){console.error("cannot access sessionStorage. Consider setting an own storage implementation using setStorage",c)}return i.setupRefreshTimer(),i}return s(e,a),e.prototype.configure=function(e){Object.assign(this,new w,e),this.config=Object.assign({},new w,e),this.sessionChecksEnabled&&this.setupSessionCheck(),this.configChanged()},e.prototype.configChanged=function(){},e.prototype.restartSessionChecksIfStillLoggedIn=function(){this.hasValidIdToken()&&this.initSessionCheck()},e.prototype.restartRefreshTimerIfStillLoggedIn=function(){this.setupExpirationTimers()},e.prototype.setupSessionCheck=function(){var t=this;this.events.pipe(l.filter(function(e){return"token_received"===e.type})).subscribe(function(e){t.initSessionCheck()})},e.prototype.setupAutomaticSilentRefresh=function(t){var n=this;void 0===t&&(t={}),this.events.pipe(l.filter(function(e){return"token_expires"===e.type})).subscribe(function(e){n.silentRefresh(t)["catch"](function(e){n.debug("automatic silent refresh did not work")})}),this.restartRefreshTimerIfStillLoggedIn()},e.prototype.loadDiscoveryDocumentAndTryLogin=function(t){var n=this;return void 0===t&&(t=null),this.loadDiscoveryDocument().then(function(e){return n.tryLogin(t)})},e.prototype.loadDiscoveryDocumentAndLogin=function(e){var t=this;return void 0===e&&(e=null),this.loadDiscoveryDocumentAndTryLogin(e).then(function(e){return!(!t.hasValidIdToken()||!t.hasValidAccessToken())||(t.initImplicitFlow(),!1)})},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.showDebugInformation&&console.debug.apply(console,e)},e.prototype.validateUrlFromDiscoveryDocument=function(e){var t=[],n=this.validateUrlForHttps(e),o=this.validateUrlAgainstIssuer(e);return n||t.push("https for all urls required. Also for urls received by discovery."),o||t.push("Every url in discovery document has to start with the issuer url.Also see property strictDiscoveryDocumentValidation."),t},e.prototype.validateUrlForHttps=function(e){if(!e)return!0;var t=e.toLowerCase();return!1===this.requireHttps||(!(!t.match(/^http:\/\/localhost($|[:\/])/)&&!t.match(/^http:\/\/localhost($|[:\/])/)||"remoteOnly"!==this.requireHttps)||t.startsWith("https://"))},e.prototype.validateUrlAgainstIssuer=function(e){return!this.strictDiscoveryDocumentValidation||(!e||e.toLowerCase().startsWith(this.issuer.toLowerCase()))},e.prototype.setupRefreshTimer=function(){var t=this;"undefined"!=typeof window?(this.hasValidIdToken()&&(this.clearAccessTokenTimer(),this.clearIdTokenTimer(),this.setupExpirationTimers()),this.events.pipe(l.filter(function(e){return"token_received"===e.type})).subscribe(function(e){t.clearAccessTokenTimer(),t.clearIdTokenTimer(),t.setupExpirationTimers()})):this.debug("timer not supported on this plattform")},e.prototype.setupExpirationTimers=function(){var e=this.getIdTokenExpiration()||Number.MAX_VALUE,t=(this.getAccessTokenExpiration()||Number.MAX_VALUE)<=e;this.hasValidAccessToken()&&t&&this.setupAccessTokenTimer(),this.hasValidIdToken()&&!t&&this.setupIdTokenTimer()},e.prototype.setupAccessTokenTimer=function(){var t=this,e=this.getAccessTokenExpiration(),n=this.getAccessTokenStoredAt(),o=this.calcTimeout(n,e);this.ngZone.runOutsideAngular(function(){t.accessTokenTimeoutSubscription=h.of(new k("token_expires","access_token")).pipe(l.delay(o)).subscribe(function(e){t.ngZone.run(function(){t.eventsSubject.next(e)})})})},e.prototype.setupIdTokenTimer=function(){var t=this,e=this.getIdTokenExpiration(),n=this.getIdTokenStoredAt(),o=this.calcTimeout(n,e);this.ngZone.runOutsideAngular(function(){t.idTokenTimeoutSubscription=h.of(new k("token_expires","id_token")).pipe(l.delay(o)).subscribe(function(e){t.ngZone.run(function(){t.eventsSubject.next(e)})})})},e.prototype.clearAccessTokenTimer=function(){this.accessTokenTimeoutSubscription&&this.accessTokenTimeoutSubscription.unsubscribe()},e.prototype.clearIdTokenTimer=function(){this.idTokenTimeoutSubscription&&this.idTokenTimeoutSubscription.unsubscribe()},e.prototype.calcTimeout=function(e,t){return(t-e)*this.timeoutFactor},e.prototype.setStorage=function(e){this._storage=e,this.configChanged()},e.prototype.loadDiscoveryDocument=function(e){var r=this;return void 0===e&&(e=null),new Promise(function(o,t){e||((e=r.issuer||"").endsWith("/")||(e+="/"),e+=".well-known/openid-configuration"),r.validateUrlForHttps(e)?r.http.get(e).subscribe(function(n){if(!r.validateDiscoveryDocument(n))return r.eventsSubject.next(new y("discovery_document_validation_error",null)),void t("discovery_document_validation_error");r.loginUrl=n.authorization_endpoint,r.logoutUrl=n.end_session_endpoint||r.logoutUrl,r.grantTypesSupported=n.grant_types_supported,r.issuer=n.issuer,r.tokenEndpoint=n.token_endpoint,r.userinfoEndpoint=n.userinfo_endpoint,r.jwksUri=n.jwks_uri,r.sessionCheckIFrameUrl=n.check_session_iframe||r.sessionCheckIFrameUrl,r.discoveryDocumentLoaded=!0,r.discoveryDocumentLoadedSubject.next(n),r.sessionChecksEnabled&&r.restartSessionChecksIfStillLoggedIn(),r.loadJwks().then(function(e){var t=new v("discovery_document_loaded",{discoveryDocument:n,jwks:e});r.eventsSubject.next(t),o(t)})["catch"](function(e){r.eventsSubject.next(new y("discovery_document_load_error",e)),t(e)})},function(e){console.error("error loading discovery document",e),r.eventsSubject.next(new y("discovery_document_load_error",e)),t(e)}):t("issuer must use Https. Also check property requireHttps.")})},e.prototype.loadJwks=function(){var o=this;return new Promise(function(t,n){o.jwksUri?o.http.get(o.jwksUri).subscribe(function(e){o.jwks=e,o.eventsSubject.next(new v("discovery_document_loaded")),t(e)},function(e){console.error("error loading jwks",e),o.eventsSubject.next(new y("jwks_load_error",e)),n(e)}):t(null)})},e.prototype.validateDiscoveryDocument=function(e){var t;return this.skipIssuerCheck||e.issuer===this.issuer?0<(t=this.validateUrlFromDiscoveryDocument(e.authorization_endpoint)).length?(console.error("error validating authorization_endpoint in discovery document",t),!1):0<(t=this.validateUrlFromDiscoveryDocument(e.end_session_endpoint)).length?(console.error("error validating end_session_endpoint in discovery document",t),!1):(0<(t=this.validateUrlFromDiscoveryDocument(e.token_endpoint)).length&&console.error("error validating token_endpoint in discovery document",t),0<(t=this.validateUrlFromDiscoveryDocument(e.userinfo_endpoint)).length?(console.error("error validating userinfo_endpoint in discovery document",t),!1):0<(t=this.validateUrlFromDiscoveryDocument(e.jwks_uri)).length?(console.error("error validating jwks_uri in discovery document",t),!1):(this.sessionChecksEnabled&&!e.check_session_iframe&&console.warn("sessionChecksEnabled is activated but discovery document does not contain a check_session_iframe field"),!0)):(console.error("invalid issuer in discovery document","expected: "+this.issuer,"current: "+e.issuer),!1)},e.prototype.fetchTokenUsingPasswordFlowAndLoadUserProfile=function(e,t,n){var o=this;return void 0===n&&(n=new f.HttpHeaders),this.fetchTokenUsingPasswordFlow(e,t,n).then(function(){return o.loadUserProfile()})},e.prototype.loadUserProfile=function(){var r=this;if(!this.hasValidAccessToken())throw new Error("Can not load User Profile without access_token");var t=this.customUserinfoEndpoint?this.customUserinfoEndpoint:this.userinfoEndpoint;if(!this.validateUrlForHttps(t))throw new Error("userinfoEndpoint must use Http. Also check property requireHttps.");var s=this.customUserinfoEndpoint?"Bearer "+this.getIdToken():"Bearer "+this.getAccessToken();return new Promise(function(n,o){var e=(new f.HttpHeaders).set("Authorization",s);r.http.get(t,{headers:e}).subscribe(function(e){r.debug("userinfo received",e);var t=r.getIdentityClaims()||{};if(r.skipSubjectCheck||!r.oidc||t.sub&&e.sub===t.sub)e=Object.assign({},t,e),r._storage.setItem("id_token_claims_obj",JSON.stringify(e)),r.eventsSubject.next(new v("user_profile_loaded")),n(e);else{o("if property oidc is true, the received user-id (sub) has to be the user-id of the user that has logged in with oidc.\nif you are not using oidc but just oauth2 password flow set oidc to false")}},function(e){console.error("error loading user info",e),r.eventsSubject.next(new y("user_profile_load_error",e)),o(e)})})},e.prototype.fetchTokenUsingPasswordFlow=function(h,l,d){var p=this;if(void 0===d&&(d=new f.HttpHeaders),!this.validateUrlForHttps(this.tokenEndpoint))throw new Error("tokenEndpoint must use Http. Also check property requireHttps.");return new Promise(function(t,n){var e,o,r=new f.HttpParams({encoder:new b}).set("grant_type","password").set("scope",p.scope).set("username",h).set("password",l);if(p.useHttpBasicAuthForPasswordFlow){var s=btoa(p.clientId+":"+p.dummyClientSecret);d=d.set("Authentication","BASIC "+s)}if(p.useHttpBasicAuthForPasswordFlow||(r=r.set("client_id",p.clientId)),!p.useHttpBasicAuthForPasswordFlow&&p.dummyClientSecret&&(r=r.set("client_secret",p.dummyClientSecret)),p.customQueryParams)try{for(var i=S(Object.getOwnPropertyNames(p.customQueryParams)),c=i.next();!c.done;c=i.next()){var a=c.value;r=r.set(a,p.customQueryParams[a])}}catch(u){e={error:u}}finally{try{c&&!c.done&&(o=i["return"])&&o.call(i)}finally{if(e)throw e.error}}d=d.set("Content-Type","application/x-www-form-urlencoded"),p.http.post(p.tokenEndpoint,r,{headers:d}).subscribe(function(e){p.debug("tokenResponse",e),p.storeAccessTokenResponse(e.access_token,e.refresh_token,e.expires_in,e.scope),p.eventsSubject.next(new v("token_received")),t(e)},function(e){console.error("Error performing password flow",e),p.eventsSubject.next(new y("token_error",e)),n(e)})})},e.prototype.refreshToken=function(){var e=(new f.HttpParams).set("grant_type","refresh_token").set("refresh_token",this._storage.getItem("refresh_token")).set("scope",this.scope),t=this._storage.getItem("nonce");return t&&this.oidc&&(e=e.set("nonce",t)),this.dummyClientSecret&&(e=e.set("client_secret",this.dummyClientSecret)),this.fetchToken(e)},e.prototype.getTokenFromCode=function(e){var t=(new f.HttpParams).set("grant_type","authorization_code").set("code",e).set("redirect_uri",this.redirectUri);return this.fetchToken(t)},e.prototype.fetchToken=function(u){var h=this;if(!this.validateUrlForHttps(this.tokenEndpoint))throw new Error("tokenEndpoint must use Http. Also check property requireHttps.");return new Promise(function(n,o){if(u=u.set("client_id",h.clientId),h.customQueryParams)try{for(var e=S(Object.getOwnPropertyNames(h.customQueryParams)),t=e.next();!t.done;t=e.next()){var r=t.value;u=u.set(r,h.customQueryParams[r])}}catch(a){s={error:a}}finally{try{t&&!t.done&&(i=e["return"])&&i.call(e)}finally{if(s)throw s.error}}var s,i,c=(new f.HttpHeaders).set("Content-Type","application/x-www-form-urlencoded");h.http.post(h.tokenEndpoint,u,{headers:c}).subscribe(function(t){h.debug("refresh tokenResponse",t),h.storeAccessTokenResponse(t.access_token,t.refresh_token,t.expires_in,t.scope),h.oidc&&t.id_token?h.processIdToken(t.id_token,t.access_token).then(function(e){h.storeIdToken(e),h.eventsSubject.next(new v("token_received")),h.eventsSubject.next(new v("token_refreshed")),n(t)})["catch"](function(e){h.eventsSubject.next(new y("token_validation_error",e)),console.error("Error validating tokens"),console.error(e),o(e)}):(h.eventsSubject.next(new v("token_received")),h.eventsSubject.next(new v("token_refreshed")),n(t))},function(e){console.error("Error getting token",e),h.eventsSubject.next(new y("token_refresh_error",e)),o(e)})})},e.prototype.removeSilentRefreshEventListener=function(){this.silentRefreshPostMessageEventListener&&(window.removeEventListener("message",this.silentRefreshPostMessageEventListener),this.silentRefreshPostMessageEventListener=null)},e.prototype.setupSilentRefreshEventListener=function(){var r=this;this.removeSilentRefreshEventListener(),this.silentRefreshPostMessageEventListener=function(e){var t="#";if(r.silentRefreshMessagePrefix&&(t+=r.silentRefreshMessagePrefix),e&&e.data&&"string"==typeof e.data){var n=e.data;if(n.startsWith(t)){var o="#"+n.substr(t.length);r.tryLogin({customHashFragment:o,preventClearHashAfterLogin:!0,onLoginError:function(e){r.eventsSubject.next(new y("silent_refresh_error",e))},onTokenReceived:function(){r.eventsSubject.next(new v("silently_refreshed"))}})["catch"](function(e){return r.debug("tryLogin during silent refresh failed",e)})}}},window.addEventListener("message",this.silentRefreshPostMessageEventListener)},e.prototype.silentRefresh=function(e,t){var n=this;void 0===e&&(e={}),void 0===t&&(t=!0);var o=this.getIdentityClaims()||{};if(this.useIdTokenHintForSilentRefresh&&this.hasValidIdToken()&&(e.id_token_hint=this.getIdToken()),!this.validateUrlForHttps(this.loginUrl))throw new Error("tokenEndpoint must use Https. Also check property requireHttps.");if("undefined"==typeof document)throw new Error("silent refresh is not supported on this platform");var r=document.getElementById(this.silentRefreshIFrameName);r&&document.body.removeChild(r),this.silentRefreshSubject=o.sub;var s=document.createElement("iframe");s.id=this.silentRefreshIFrameName,this.setupSilentRefreshEventListener();var i=this.silentRefreshRedirectUri||this.redirectUri;this.createLoginUrl(null,null,i,t,e).then(function(e){s.setAttribute("src",e),n.silentRefreshShowIFrame||(s.style.display="none"),document.body.appendChild(s)});var c=this.events.pipe(l.filter(function(e){return e instanceof y}),l.first()),a=this.events.pipe(l.filter(function(e){return"silently_refreshed"===e.type}),l.first()),u=h.of(new y("silent_refresh_timeout",null)).pipe(l.delay(this.silentRefreshTimeout));return h.race([c,a,u]).pipe(l.tap(function(e){"silent_refresh_timeout"===e.type&&n.eventsSubject.next(e)}),l.map(function(e){if(e instanceof y)throw e;return e})).toPromise()},e.prototype.canPerformSessionCheck=function(){return!!this.sessionChecksEnabled&&(this.sessionCheckIFrameUrl?this.getSessionState()?"undefined"!=typeof document:(console.warn("sessionChecksEnabled is activated but there is no session_state"),!1):(console.warn("sessionChecksEnabled is activated but there is no sessionCheckIFrameUrl"),!1))},e.prototype.setupSessionCheckEventListener=function(){var o=this;this.removeSessionCheckEventListener(),this.sessionCheckEventListener=function(e){var t=e.origin.toLowerCase(),n=o.issuer.toLowerCase();switch(o.debug("sessionCheckEventListener"),n.startsWith(t)||o.debug("sessionCheckEventListener","wrong origin",t,"expected",n),e.data){case"unchanged":o.handleSessionUnchanged();break;case"changed":o.handleSessionChange();break;case"error":o.handleSessionError()}o.debug("got info from session check inframe",e)},window.addEventListener("message",this.sessionCheckEventListener)},e.prototype.handleSessionUnchanged=function(){this.debug("session check","session unchanged")},e.prototype.handleSessionChange=function(){var t=this;this.eventsSubject.next(new k("session_changed")),this.stopSessionCheckTimer(),this.silentRefreshRedirectUri?(this.silentRefresh()["catch"](function(e){return t.debug("silent refresh failed after session changed")}),this.waitForSilentRefreshAfterSessionChange()):(this.eventsSubject.next(new k("session_terminated")),this.logOut(!0))},e.prototype.waitForSilentRefreshAfterSessionChange=function(){var t=this;this.events.pipe(l.filter(function(e){return"silently_refreshed"===e.type||"silent_refresh_timeout"===e.type||"silent_refresh_error"===e.type}),l.first()).subscribe(function(e){"silently_refreshed"!==e.type&&(t.debug("silent refresh did not work after session changed"),t.eventsSubject.next(new k("session_terminated")),t.logOut(!0))})},e.prototype.handleSessionError=function(){this.stopSessionCheckTimer(),this.eventsSubject.next(new k("session_error"))},e.prototype.removeSessionCheckEventListener=function(){this.sessionCheckEventListener&&(window.removeEventListener("message",this.sessionCheckEventListener),this.sessionCheckEventListener=null)},e.prototype.initSessionCheck=function(){if(this.canPerformSessionCheck()){var e=document.getElementById(this.sessionCheckIFrameName);e&&document.body.removeChild(e);var t=document.createElement("iframe");t.id=this.sessionCheckIFrameName,this.setupSessionCheckEventListener();var n=this.sessionCheckIFrameUrl;t.setAttribute("src",n),t.style.display="none",document.body.appendChild(t),this.startSessionCheckTimer()}},e.prototype.startSessionCheckTimer=function(){this.stopSessionCheckTimer(),this.sessionCheckTimer=setInterval(this.checkSession.bind(this),this.sessionCheckIntervall)},e.prototype.stopSessionCheckTimer=function(){this.sessionCheckTimer&&(clearInterval(this.sessionCheckTimer),this.sessionCheckTimer=null)},e.prototype.checkSession=function(){var e=document.getElementById(this.sessionCheckIFrameName);e||console.warn("checkSession did not find iframe",this.sessionCheckIFrameName);var t=this.getSessionState();t||this.stopSessionCheckTimer();var n=this.clientId+" "+t;e.contentWindow.postMessage(n,this.issuer)},e.prototype.createLoginUrl=function(e,t,n,o,r){void 0===e&&(e=""),void 0===t&&(t=""),void 0===n&&(n=""),void 0===o&&(o=!1),void 0===r&&(r={});var s,i=this;s=n||this.redirectUri;var c=null;if(this.disableNonceCheck||(c=this.createAndSaveNonce(),e=e?c+this.config.nonceStateSeparator+e:c),!this.requestAccessToken&&!this.oidc)throw new Error("Either requestAccessToken or oidc or both must be true");this.responseType=this.getResponseType(this.inImplicitFlow);var a=-1<i.loginUrl.indexOf("?")?"&":"?",u=i.scope;this.oidc&&!u.match(/(^|\s)openid($|\s)/)&&(u="openid "+u);var h,l,d,p,f=i.loginUrl+a+"response_type="+encodeURIComponent(i.responseType)+"&client_id="+encodeURIComponent(i.clientId)+"&state="+encodeURIComponent(e)+"&redirect_uri="+encodeURIComponent(s)+"&scope="+encodeURIComponent(u);t&&(f+="&login_hint="+encodeURIComponent(t)),i.resource&&(f+="&resource="+encodeURIComponent(i.resource)),c&&this.oidc&&(f+="&nonce="+encodeURIComponent(c)),o&&(f+="&prompt=none");try{for(var m=S(Object.keys(r)),g=m.next();!g.done;g=m.next()){var v=g.value;f+="&"+encodeURIComponent(v)+"="+encodeURIComponent(r[v])}}catch(_){h={error:_}}finally{try{g&&!g.done&&(l=m["return"])&&l.call(m)}finally{if(h)throw h.error}}if(this.customQueryParams)try{for(var k=S(Object.getOwnPropertyNames(this.customQueryParams)),y=k.next();!y.done;y=k.next()){f+="&"+(v=y.value)+"="+encodeURIComponent(this.customQueryParams[v])}}catch(w){d={error:w}}finally{try{y&&!y.done&&(p=k["return"])&&p.call(k)}finally{if(d)throw d.error}}return Promise.resolve(f)},e.prototype.initImplicitFlowInternal=function(e,t){var n=this;if(void 0===e&&(e=""),void 0===t&&(t=""),!this.inImplicitFlow){if(this.inImplicitFlow=!0,!this.validateUrlForHttps(this.loginUrl))throw new Error("loginUrl must use Http. Also check property requireHttps.");var o={},r=null;"string"==typeof t?r=t:"object"==typeof t&&(o=t),this.createLoginUrl(e,r,null,!1,o).then(function(e){location.href=e})["catch"](function(e){console.error("Error in initImplicitFlow"),console.error(e),n.inImplicitFlow=!1})}},e.prototype.initImplicitFlow=function(t,n){var o=this;void 0===t&&(t=""),void 0===n&&(n=""),""!==this.loginUrl?this.initImplicitFlowInternal(t,n):this.events.pipe(l.filter(function(e){return"discovery_document_loaded"===e.type})).subscribe(function(e){return o.initImplicitFlowInternal(t,n)})},e.prototype.initAuthorizationCodeFlow=function(){var t=this;""!==this.loginUrl?this.initAuthorizationCodeFlowInternal():this.events.pipe(l.filter(function(e){return"discovery_document_loaded"===e.type})).subscribe(function(e){return t.initAuthorizationCodeFlowInternal()})},e.prototype.initAuthorizationCodeFlowInternal=function(){if(!this.validateUrlForHttps(this.loginUrl))throw new Error("loginUrl must use Http. Also check property requireHttps.");this.createLoginUrl("","",null,!1,{}).then(function(e){location.href=e})["catch"](function(e){console.error("Error in initAuthorizationCodeFlow"),console.error(e)})},e.prototype.getResponseType=function(e){return e?this.oidc&&this.requestAccessToken?"id_token token":this.oidc&&!this.requestAccessToken?"id_token":"token":"code"},e.prototype.callOnTokenReceivedIfExists=function(e){if(e.onTokenReceived){var t={idClaims:this.getIdentityClaims(),idToken:this.getIdToken(),accessToken:this.getAccessToken(),state:this.state};e.onTokenReceived(t)}},e.prototype.storeAccessTokenResponse=function(e,t,n,o){if(this._storage.setItem("access_token",e),o&&this._storage.setItem("granted_scopes",JSON.stringify(o.split("+"))),this._storage.setItem("access_token_stored_at",""+Date.now()),n){var r=1e3*n,s=(new Date).getTime()+r;this._storage.setItem("expires_at",""+s)}t&&this._storage.setItem("refresh_token",t)},e.prototype.tryLogin=function(e){return void 0===e&&(e=null),e=e||{},this.requestAccessToken||this.oidc?window.location.search&&(window.location.search.startsWith("?code=")||window.location.search.includes("&code="))?this.tryLoginAuthorizationCode():this.tryLoginImplicit(e):Promise.reject("Either requestAccessToken or oidc or both must be true.")},e.prototype.tryLoginAuthorizationCode=function(){var e=this,t=window.location.search.split("?")[1].split("&").filter(function(e){return e.includes("code=")}),o=t.length?t[0].split("code=")[1]:undefined;return o?new Promise(function(t,n){e.getTokenFromCode(o).then(function(e){t()})["catch"](function(e){n(e)})}):Promise.resolve()},e.prototype.tryLoginImplicit=function(n){var e,t=this;void 0===n&&(n=null),e=(n=n||{}).customHashFragment?this.urlHelper.getHashFragmentParams(n.customHashFragment):this.urlHelper.getHashFragmentParams(),this.debug("parsed url",e);var o=e.state,r=o;if(o){var s=o.indexOf(this.config.nonceStateSeparator);-1<s&&(r=o.substr(0,s),this.state=o.substr(s+this.config.nonceStateSeparator.length))}if(e.error){this.debug("error trying to login"),this.handleLoginError(n,e);var i=new y("token_error",{},e);return this.eventsSubject.next(i),Promise.reject(i)}var c=e.access_token,a=e.id_token,u=e.session_state,h=e.scope;if(!this.requestAccessToken&&!this.oidc)return Promise.reject("Either requestAccessToken or oidc or both must be true.");if(this.requestAccessToken&&!c)return Promise.resolve();if(this.requestAccessToken&&!n.disableOAuth2StateCheck&&!o)return Promise.resolve();if(this.oidc&&!a)return Promise.resolve();if((this.sessionChecksEnabled&&!u&&console.warn("session checks (Session Status Change Notification) is activated in the configuration but the id_token does not contain a session_state claim"),this.requestAccessToken&&!n.disableOAuth2StateCheck)&&!this.validateNonceForAccessToken(c,r)){var l=new y("invalid_nonce_in_state",null);return this.eventsSubject.next(l),Promise.reject(l)}return this.requestAccessToken&&this.storeAccessTokenResponse(c,null,e.expires_in||this.fallbackAccessTokenExpirationTimeInSec,h),this.oidc?this.processIdToken(a,c).then(function(t){return n.validationHandler?n.validationHandler({accessToken:c,idClaims:t.idTokenClaims,idToken:t.idToken,state:o}).then(function(e){return t}):t}).then(function(e){t.storeIdToken(e),t.storeSessionState(u),t.clearHashAfterLogin&&(location.hash=""),t.eventsSubject.next(new v("token_received")),t.callOnTokenReceivedIfExists(n),t.inImplicitFlow=!1})["catch"](function(e){return t.eventsSubject.next(new y("token_validation_error",e)),console.error("Error validating tokens"),console.error(e),Promise.reject(e)}):(this.eventsSubject.next(new v("token_received")),this.clearHashAfterLogin&&!n.preventClearHashAfterLogin&&(location.hash=""),Promise.resolve())},e.prototype.validateNonceForAccessToken=function(e,t){var n=this._storage.getItem("nonce");if(n!==t){return console.error("validating access_token failed. wrong state/nonce.",n,t),!1}return!0},e.prototype.storeIdToken=function(e){this._storage.setItem("id_token",e.idToken),this._storage.setItem("id_token_claims_obj",e.idTokenClaimsJson),this._storage.setItem("id_token_expires_at",""+e.idTokenExpiresAt),this._storage.setItem("id_token_stored_at",""+Date.now())},e.prototype.storeSessionState=function(e){this._storage.setItem("session_state",e)},e.prototype.getSessionState=function(){return this._storage.getItem("session_state")},e.prototype.handleLoginError=function(e,t){e.onLoginError&&e.onLoginError(t),this.clearHashAfterLogin&&(location.hash="")},e.prototype.processIdToken=function(t,e){var n=this,o=t.split("."),r=_(this.padBase64(o[0])),s=JSON.parse(r),i=_(this.padBase64(o[1])),c=JSON.parse(i),a=this._storage.getItem("nonce");if(Array.isArray(c.aud)){if(c.aud.every(function(e){return e!==n.clientId})){var u="Wrong audience: "+c.aud.join(",");return console.warn(u),Promise.reject(u)}}else if(c.aud!==this.clientId){u="Wrong audience: "+c.aud;return console.warn(u),Promise.reject(u)}if(!c.sub){u="No sub claim in id_token";return console.warn(u),Promise.reject(u)}if(this.sessionChecksEnabled&&this.silentRefreshSubject&&this.silentRefreshSubject!==c.sub){u="After refreshing, we got an id_token for another user (sub). Expected sub: "+this.silentRefreshSubject+", received sub: "+c.sub;return console.warn(u),Promise.reject(u)}if(!c.iat){u="No iat claim in id_token";return console.warn(u),Promise.reject(u)}if(c.iss!==this.issuer){u="Wrong issuer: "+c.iss;return console.warn(u),Promise.reject(u)}if(!this.disableNonceCheck&&c.nonce!==a){u="Wrong nonce: "+c.nonce;return console.warn(u),Promise.reject(u)}if(!this.disableAtHashCheck&&this.requestAccessToken&&!c.at_hash){u="An at_hash is needed!";return console.warn(u),Promise.reject(u)}var h=Date.now(),l=1e3*c.iat,d=1e3*c.exp;if(h<=l-6e5||d+6e5<=h){u="Token has been expired";return console.error(u),console.error({now:h,issuedAtMSec:l,expiresAtMSec:d}),Promise.reject(u)}var p={accessToken:e,idToken:t,jwks:this.jwks,idTokenClaims:c,idTokenHeader:s,loadKeys:function(){return n.loadJwks()}};if(!this.disableAtHashCheck&&this.requestAccessToken&&!this.checkAtHash(p)){u="Wrong at_hash";return console.warn(u),Promise.reject(u)}return this.checkSignature(p).then(function(e){return{idToken:t,idTokenClaims:c,idTokenClaimsJson:i,idTokenHeader:s,idTokenHeaderJson:r,idTokenExpiresAt:d}})},e.prototype.getIdentityClaims=function(){var e=this._storage.getItem("id_token_claims_obj");return e?JSON.parse(e):null},e.prototype.getGrantedScopes=function(){var e=this._storage.getItem("granted_scopes");return e?JSON.parse(e):null},e.prototype.getIdToken=function(){return this._storage?this._storage.getItem("id_token"):null},e.prototype.padBase64=function(e){for(;e.length%4!=0;)e+="=";return e},e.prototype.getAccessToken=function(){return this._storage.getItem("access_token")},e.prototype.getRefreshToken=function(){return this._storage.getItem("refresh_token")},e.prototype.getAccessTokenExpiration=function(){return this._storage.getItem("expires_at")?parseInt(this._storage.getItem("expires_at"),10):null},e.prototype.getAccessTokenStoredAt=function(){return parseInt(this._storage.getItem("access_token_stored_at"),10)},e.prototype.getIdTokenStoredAt=function(){return parseInt(this._storage.getItem("id_token_stored_at"),10)},e.prototype.getIdTokenExpiration=function(){return this._storage.getItem("id_token_expires_at")?parseInt(this._storage.getItem("id_token_expires_at"),10):null},e.prototype.hasValidAccessToken=function(){if(this.getAccessToken()){var e=this._storage.getItem("expires_at"),t=new Date;return!(e&&parseInt(e,10)<t.getTime())}return!1},e.prototype.hasValidIdToken=function(){if(this.getIdToken()){var e=this._storage.getItem("id_token_expires_at"),t=new Date;return!(e&&parseInt(e,10)<t.getTime())}return!1},e.prototype.authorizationHeader=function(){return"Bearer "+this.getAccessToken()},e.prototype.getAuthorizationHeader=function(){var t=this;return this.hasValidAccessToken()?Promise.resolve(this.authorizationHeader()):this.getRefreshToken()?(console.log("Session no longer valid. Try to get new one using refresh token"),this.refreshToken().then(function(e){return t.hasValidAccessToken()?Promise.resolve(t.authorizationHeader()):Promise.reject("Unable to refresh token")})["catch"](function(e){return t.clearStorage(),Promise.reject("Unable to refresh token - "+e)})):(this.clearStorage(),Promise.reject("No refresh token available"))},e.prototype.logOut=function(e){void 0===e&&(e=!1);var t=this.getIdToken();if(this.clearStorage(),this.silentRefreshSubject=null,this.eventsSubject.next(new k("logout")),this.logoutUrl&&!e&&t){var n;if(!this.validateUrlForHttps(this.logoutUrl))throw new Error("logoutUrl must use Http. Also check property requireHttps.");n=-1<this.logoutUrl.indexOf("{{")?this.logoutUrl.replace(/\{\{id_token\}\}/,t).replace(/\{\{client_id\}\}/,this.clientId):this.logoutUrl+(-1<this.logoutUrl.indexOf("?")?"&":"?")+"id_token_hint="+encodeURIComponent(t)+"&post_logout_redirect_uri="+encodeURIComponent(this.postLogoutRedirectUri||this.redirectUri),location.href=n}},e.prototype.clearStorage=function(){this._storage.removeItem("access_token"),this._storage.removeItem("id_token"),this._storage.removeItem("refresh_token"),this._storage.removeItem("nonce"),this._storage.removeItem("expires_at"),this._storage.removeItem("id_token_claims_obj"),this._storage.removeItem("id_token_expires_at"),this._storage.removeItem("id_token_stored_at"),this._storage.removeItem("access_token_stored_at")},e.prototype.createAndSaveNonce=function(){var e=this.createNonce();return this._storage.setItem("nonce",e),e},e.prototype.createNonce=function(){if(this.rngUrl)throw new Error("createNonce with rng-web-api has not been implemented so far");for(var e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=0;n<40;n++)e+=t.charAt(Math.floor(Math.random()*t.length));return e},e.prototype.checkAtHash=function(e){return this.tokenValidationHandler?this.tokenValidationHandler.validateAtHash(e):(console.warn("No tokenValidationHandler configured. Cannot check at_hash."),!0)},e.prototype.checkSignature=function(e){return this.tokenValidationHandler?this.tokenValidationHandler.validateSignature(e):(console.warn("No tokenValidationHandler configured. Cannot check signature."),Promise.resolve(null))},e}(w);T.decorators=[{type:t.Injectable}],T.ctorParameters=function(){return[{type:t.NgZone},{type:f.HttpClient},{type:c,decorators:[{type:t.Optional}]},{type:u,decorators:[{type:t.Optional}]},{type:w,decorators:[{type:t.Optional}]},{type:m}]};var I=function(){},C=function(){},A=function(){},E=function(){function e(){}return e.prototype.handleError=function(e){return h.throwError(e)},e}(),j=function(){function e(e,t,n){this.authStorage=e,this.errorHandler=t,this.moduleConfig=n}return e.prototype.checkUrl=function(t){return!!this.moduleConfig.resourceServer.allowedUrls.find(function(e){return t.startsWith(e)})},e.prototype.intercept=function(e,t){var n=this,o=e.url.toLowerCase();if(!this.moduleConfig)return t.handle(e);if(!this.moduleConfig.resourceServer)return t.handle(e);if(this.moduleConfig.resourceServer.allowedUrls&&!this.checkUrl(o))return t.handle(e);if(this.moduleConfig.resourceServer.sendAccessToken&&this.authStorage.getItem("access_token")){var r="Bearer "+this.authStorage.getItem("access_token"),s=e.headers.set("Authorization",r);e=e.clone({headers:s})}return t.handle(e).pipe(l.catchError(function(e){return n.errorHandler.handleError(e)}))},e}();j.decorators=[{type:t.Injectable}],j.ctorParameters=function(){return[{type:c},{type:A},{type:I,decorators:[{type:t.Optional}]}]};var U=function(){function e(){}return e.prototype.validateSignature=function(e){return Promise.resolve(null)},e.prototype.validateAtHash=function(e){return!0},e}();function H(){return"undefined"!=typeof sessionStorage?sessionStorage:null}var x=function(){function n(){}return n.forRoot=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=U),{ngModule:n,providers:[T,m,{provide:c,useFactory:H},{provide:u,useClass:t},{provide:A,useClass:E},{provide:I,useValue:e},{provide:f.HTTP_INTERCEPTORS,useClass:j,multi:!0}]}},n}();x.decorators=[{type:t.NgModule,args:[{imports:[n.CommonModule],declarations:[],exports:[]}]}];var P=function(t){function e(){var e=t.apply(this,function(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(r(arguments[t]));return e}(arguments))||this;return e.allowedAlgorithms=["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","PS256","PS384","PS512"],e.gracePeriodInSec=600,e}return s(e,t),e.prototype.validateSignature=function(t,e){var n=this;if(void 0===e&&(e=!1),!t.idToken)throw new Error("Parameter idToken expected!");if(!t.idTokenHeader)throw new Error("Parameter idTokenHandler expected.");if(!t.jwks)throw new Error("Parameter jwks expected!");if(!t.jwks.keys||!Array.isArray(t.jwks.keys)||0===t.jwks.keys.length)throw new Error("Array keys in jwks missing!");var o,r=t.idTokenHeader.kid,s=t.jwks.keys,i=t.idTokenHeader.alg;if(r)o=s.find(function(e){return e.kid===r});else{var c=this.alg2kty(i),a=s.filter(function(e){return e.kty===c&&"sig"===e.use});if(1<a.length){var u="More than one matching key found. Please specify a kid in the id_token header.";return console.error(u),Promise.reject(u)}1===a.length&&(o=a[0])}if(!o&&!e&&t.loadKeys)return t.loadKeys().then(function(e){return t.jwks=e}).then(function(e){return n.validateSignature(t,!0)});if(!o&&e&&!r){u="No matching key found.";return console.error(u),Promise.reject(u)}if(!o&&e&&r){u="expected key not found in property jwks. This property is most likely loaded with the discovery document. Expected key id (kid): "+r;return console.error(u),Promise.reject(u)}var h=d.KEYUTIL.getKey(o),l={alg:this.allowedAlgorithms,gracePeriod:this.gracePeriodInSec};return d.KJUR.jws.JWS.verifyJWT(t.idToken,h,l)?Promise.resolve():Promise.reject("Signature not valid")},e.prototype.alg2kty=function(e){switch(e.charAt(0)){case"R":return"RSA";case"E":return"EC";default:throw new Error("Cannot infer kty from alg: "+e)}},e.prototype.calcHash=function(e,t){var n=new d.KJUR.crypto.MessageDigest({alg:t}).digestString(e);return this.toByteArrayAsString(n)},e.prototype.toByteArrayAsString=function(e){for(var t="",n=0;n<e.length;n+=2){var o=e.charAt(n)+e.charAt(n+1),r=parseInt(o,16);t+=String.fromCharCode(r)}return t},e}(p),R=new t.InjectionToken("AUTH_CONFIG");e.createDefaultStorage=H,e.OAuthModule=x,e.OAuthService=T,e.JwksValidationHandler=P,e.NullValidationHandler=U,e.ValidationHandler=u,e.AbstractValidationHandler=p,e.UrlHelperService=m,e.AuthConfig=w,e.LoginOptions=i,e.OAuthStorage=c,e.ReceivedTokens=a,e.AUTH_CONFIG=R,e.OAuthEvent=g,e.OAuthSuccessEvent=v,e.OAuthInfoEvent=k,e.OAuthErrorEvent=y,e.DefaultOAuthInterceptor=j,e.OAuthResourceServerErrorHandler=A,e.OAuthNoopResourceServerErrorHandler=E,e.OAuthModuleConfig=I,e.OAuthResourceServerConfig=C,Object.defineProperty(e,"__esModule",{value:!0})});
//# sourceMappingURL=angular-oauth2-oidc-codeflow-pkce.umd.min.js.map