UNPKG

angular-oauth2-oidc

Version:

Support for OAuth 2(.1) and OpenId Connect (OIDC) in Angular

966 lines (948 loc) 36.7 kB
import * as i0 from '@angular/core'; import { ModuleWithProviders, OnDestroy, NgZone, InjectionToken, EnvironmentProviders } from '@angular/core'; import * as i1 from '@angular/common'; import { HttpClient, HttpHeaders, HttpResponse, HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'; import { Observable, Subject, Subscription } from 'rxjs'; declare abstract class OAuthModuleConfig { resourceServer: OAuthResourceServerConfig; } declare abstract class OAuthResourceServerConfig { /** * Urls for which calls should be intercepted. * If there is an ResourceServerErrorHandler registered, it is used for them. * If sendAccessToken is set to true, the access_token is send to them too. */ allowedUrls?: Array<string>; sendAccessToken: boolean; customUrlValidation?: (url: string) => boolean; } interface ValidationParams { idToken: string; accessToken: string; idTokenHeader: object; idTokenClaims: object; jwks: object; loadKeys: () => Promise<object>; } /** * Interface for Handlers that are hooked in to * validate tokens. */ declare abstract class ValidationHandler { /** * Validates the signature of an id_token. */ abstract validateSignature(validationParams: ValidationParams): Promise<any>; /** * Validates the at_hash in an id_token against the received access_token. */ abstract validateAtHash(validationParams: ValidationParams): Promise<boolean>; } /** * This abstract implementation of ValidationHandler already implements * the method validateAtHash. However, to make use of it, * you have to override the method calcHash. */ declare abstract class AbstractValidationHandler implements ValidationHandler { /** * Validates the signature of an id_token. */ abstract validateSignature(validationParams: ValidationParams): Promise<any>; /** * Validates the at_hash in an id_token against the received access_token. */ validateAtHash(params: ValidationParams): Promise<boolean>; /** * Infers the name of the hash algorithm to use * from the alg field of an id_token. * * @param jwtHeader the id_token's parsed header */ protected inferHashAlgorithm(jwtHeader: object): string; /** * Calculates the hash for the passed value by using * the passed hash algorithm. * * @param valueToHash * @param algorithm */ protected abstract calcHash(valueToHash: string, algorithm: string): Promise<string>; } /** * A validation handler that isn't validating nothing. * Can be used to skip validation (at your own risk). */ declare class NullValidationHandler implements ValidationHandler { validateSignature(validationParams: ValidationParams): Promise<any>; validateAtHash(validationParams: ValidationParams): Promise<boolean>; } declare class OAuthModule { static forRoot(config?: OAuthModuleConfig, validationHandlerClass?: typeof NullValidationHandler): ModuleWithProviders<OAuthModule>; static ɵfac: i0.ɵɵFactoryDeclaration<OAuthModule, never>; static ɵmod: i0.ɵɵNgModuleDeclaration<OAuthModule, never, [typeof i1.CommonModule], never>; static ɵinj: i0.ɵɵInjectorDeclaration<OAuthModule>; } declare abstract class DateTimeProvider { abstract now(): number; abstract new(): Date; } declare class SystemDateTimeProvider extends DateTimeProvider { now(): number; new(): Date; static ɵfac: i0.ɵɵFactoryDeclaration<SystemDateTimeProvider, never>; static ɵprov: i0.ɵɵInjectableDeclaration<SystemDateTimeProvider>; } declare class UrlHelperService { getHashFragmentParams(customHashFragment?: string): object; parseQueryString(queryString: string): object; static ɵfac: i0.ɵɵFactoryDeclaration<UrlHelperService, never>; static ɵprov: i0.ɵɵInjectableDeclaration<UrlHelperService>; } type EventType = 'discovery_document_loaded' | 'jwks_load_error' | 'invalid_nonce_in_state' | 'discovery_document_load_error' | 'discovery_document_validation_error' | 'user_profile_loaded' | 'user_profile_load_error' | 'token_received' | 'token_error' | 'code_error' | 'token_refreshed' | 'token_refresh_error' | 'silent_refresh_error' | 'silently_refreshed' | 'silent_refresh_timeout' | 'token_validation_error' | 'token_expires' | 'session_changed' | 'session_error' | 'session_terminated' | 'session_unchanged' | 'logout' | 'popup_closed' | 'popup_blocked' | 'token_revoke_error'; declare abstract class OAuthEvent { readonly type: EventType; constructor(type: EventType); } declare class OAuthSuccessEvent extends OAuthEvent { readonly info: any; constructor(type: EventType, info?: any); } declare class OAuthInfoEvent extends OAuthEvent { readonly info: any; constructor(type: EventType, info?: any); } declare class OAuthErrorEvent extends OAuthEvent { readonly reason: object; readonly params: object; constructor(type: EventType, reason: object, params?: object); } /** * Additional options that can be passed to tryLogin. */ declare class LoginOptions { /** * Is called, after a token has been received and * successfully validated. * * Deprecated: Use property ``events`` on OAuthService instead. */ onTokenReceived?: (receivedTokens: ReceivedTokens) => void; /** * Hook, to validate the received tokens. * * Deprecated: Use property ``tokenValidationHandler`` on OAuthService instead. */ validationHandler?: (receivedTokens: ReceivedTokens) => Promise<any>; /** * Called when tryLogin detects that the auth server * included an error message into the hash fragment. * * Deprecated: Use property ``events`` on OAuthService instead. */ onLoginError?: (params: object) => void; /** * A custom hash fragment to be used instead of the * actual one. This is used for silent refreshes, to * pass the iframes hash fragment to this method, and * is also used by popup flows in the same manner. * This can be used with code flow, where is must be set * to a hash symbol followed by the querystring. The * question mark is optional, but may be present following * the hash symbol. */ customHashFragment?: string; /** * Set this to true to disable the oauth2 state * check which is a best practice to avoid * security attacks. * As OIDC defines a nonce check that includes * this, this can be set to true when only doing * OIDC. */ disableOAuth2StateCheck?: boolean; /** * Set this to true to disable the nonce * check which is used to avoid * replay attacks. * This flag should never be true in * production environments. */ disableNonceCheck?: boolean; /** * Normally, you want to clear your hash fragment after * the lib read the token(s) so that they are not displayed * anymore in the url. If not, set this to true. For code flow * this controls removing query string values. */ preventClearHashAfterLogin?: boolean; /** * Set this for code flow if you used a custom redirect Uri * when retrieving the code. This is used internally for silent * refresh and popup flows. */ customRedirectUri?: string; } /** * Defines the logging interface the OAuthService uses * internally. Is compatible with the `console` object, * but you can provide your own implementation as well * through dependency injection. */ declare abstract class OAuthLogger { abstract debug(message?: any, ...optionalParams: any[]): void; abstract info(message?: any, ...optionalParams: any[]): void; abstract log(message?: any, ...optionalParams: any[]): void; abstract warn(message?: any, ...optionalParams: any[]): void; abstract error(message?: any, ...optionalParams: any[]): void; } /** * Defines a simple storage that can be used for * storing the tokens at client side. * Is compatible to localStorage and sessionStorage, * but you can also create your own implementations. */ declare abstract class OAuthStorage { abstract getItem(key: string): string | null; abstract removeItem(key: string): void; abstract setItem(key: string, data: string): void; } declare class MemoryStorage implements OAuthStorage { private data; getItem(key: string): string; removeItem(key: string): void; setItem(key: string, data: string): void; static ɵfac: i0.ɵɵFactoryDeclaration<MemoryStorage, never>; static ɵprov: i0.ɵɵInjectableDeclaration<MemoryStorage>; } /** * Represents the received tokens, the received state * and the parsed claims from the id-token. */ declare class ReceivedTokens { idToken: string; accessToken: string; idClaims?: object; state?: string; } /** * Represents the parsed and validated id_token. */ interface ParsedIdToken { idToken: string; idTokenClaims: object; idTokenHeader: object; idTokenClaimsJson: string; idTokenHeaderJson: string; idTokenExpiresAt: number; } /** * Represents the response from the token endpoint * http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint */ interface TokenResponse { access_token: string; id_token: string; token_type: string; expires_in: number; refresh_token: string; scope: string; state?: string; } /** * Represents the response from the user info endpoint * http://openid.net/specs/openid-connect-core-1_0.html#UserInfo */ interface UserInfo { sub: string; [key: string]: any; } /** * Represents an OpenID Connect discovery document */ interface OidcDiscoveryDoc { issuer: string; authorization_endpoint: string; token_endpoint: string; token_endpoint_auth_methods_supported: string[]; token_endpoint_auth_signing_alg_values_supported: string[]; userinfo_endpoint: string; check_session_iframe: string; end_session_endpoint: string; jwks_uri: string; registration_endpoint: string; scopes_supported: string[]; response_types_supported: string[]; acr_values_supported: string[]; response_modes_supported: string[]; grant_types_supported: string[]; subject_types_supported: string[]; userinfo_signing_alg_values_supported: string[]; userinfo_encryption_alg_values_supported: string[]; userinfo_encryption_enc_values_supported: string[]; id_token_signing_alg_values_supported: string[]; id_token_encryption_alg_values_supported: string[]; id_token_encryption_enc_values_supported: string[]; request_object_signing_alg_values_supported: string[]; display_values_supported: string[]; claim_types_supported: string[]; claims_supported: string[]; claims_parameter_supported: boolean; service_documentation: string; ui_locales_supported: string[]; revocation_endpoint: string; } declare class AuthConfig { /** * The client's id as registered with the auth server */ clientId?: string; /** * The client's redirectUri as registered with the auth server */ redirectUri?: string; /** * An optional second redirectUri where the auth server * redirects the user to after logging out. */ postLogoutRedirectUri?: string; /** * Defines whether to use 'redirectUri' as a replacement * of 'postLogoutRedirectUri' if the latter is not set. */ redirectUriAsPostLogoutRedirectUriFallback?: boolean; /** * The auth server's endpoint that allows to log * the user in when using implicit flow. */ loginUrl?: string; /** * The requested scopes */ scope?: string; resource?: string; rngUrl?: string; /** * Defines whether to use OpenId Connect during * implicit flow. */ oidc?: boolean; /** * Defines whether to request an access token during * implicit flow. */ requestAccessToken?: boolean; options?: any; /** * The issuer's uri. */ issuer?: string; /** * The logout url. */ logoutUrl?: string; /** * Defines whether to clear the hash fragment after logging in. */ clearHashAfterLogin?: boolean; /** * Url of the token endpoint as defined by OpenId Connect and OAuth 2. */ tokenEndpoint?: string; /** * Url of the revocation endpoint as defined by OpenId Connect and OAuth 2. */ revocationEndpoint?: string; /** * Names of known parameters sent out in the TokenResponse. https://tools.ietf.org/html/rfc6749#section-5.1 */ customTokenParameters?: string[]; /** * Url of the userinfo endpoint as defined by OpenId Connect. */ userinfoEndpoint?: string; responseType?: string; /** * Defines whether additional debug information should * be shown at the console. Note that in certain browsers * the verbosity of the console needs to be explicitly set * to include Debug level messages. */ showDebugInformation?: boolean; /** * The redirect uri used when doing silent refresh. */ silentRefreshRedirectUri?: string; silentRefreshMessagePrefix?: string; /** * Set this to true to display the iframe used for * silent refresh for debugging. */ silentRefreshShowIFrame?: boolean; /** * Timeout for silent refresh. * @internal * @deprecated use silentRefreshTimeout */ siletRefreshTimeout?: number; /** * Timeout for silent refresh. */ silentRefreshTimeout?: number; /** * Some auth servers don't allow using password flow * w/o a client secret while the standards do not * demand for it. In this case, you can set a password * here. As this password is exposed to the public * it does not bring additional security and is therefore * as good as using no password. */ dummyClientSecret?: string; /** * Defines whether https is required. * The default value is remoteOnly which only allows * http for localhost, while every other domains need * to be used with https. */ requireHttps?: boolean | 'remoteOnly'; /** * Defines whether every url provided by the discovery * document has to start with the issuer's url. */ strictDiscoveryDocumentValidation?: boolean; /** * JSON Web Key Set (https://tools.ietf.org/html/rfc7517) * with keys used to validate received id_tokens. * This is taken out of the disovery document. Can be set manually too. */ jwks?: object; /** * Map with additional query parameter that are appended to * the request when initializing implicit flow. */ customQueryParams?: object; silentRefreshIFrameName?: string; /** * Defines when the token_timeout event should be raised. * If you set this to the default value 0.75, the event * is triggered after 75% of the token's life time. */ timeoutFactor?: number; /** * If true, the lib will try to check whether the user * is still logged in on a regular basis as described * in http://openid.net/specs/openid-connect-session-1_0.html#ChangeNotification */ sessionChecksEnabled?: boolean; /** * Interval in msec for checking the session * according to http://openid.net/specs/openid-connect-session-1_0.html#ChangeNotification */ sessionCheckIntervall?: number; /** * Url for the iframe used for session checks */ sessionCheckIFrameUrl?: string; /** * Name of the iframe to use for session checks */ sessionCheckIFrameName?: string; /** * This property has been introduced to disable at_hash checks * and is indented for Identity Provider that does not deliver * an at_hash EVEN THOUGH its recommended by the OIDC specs. * Of course, when disabling these checks then we are bypassing * a security check which means we are more vulnerable. */ disableAtHashCheck?: boolean; /** * Defines wether to check the subject of a refreshed token after silent refresh. * Normally, it should be the same as before. */ skipSubjectCheck?: boolean; useIdTokenHintForSilentRefresh?: boolean; /** * Defined whether to skip the validation of the issuer in the discovery document. * Normally, the discovey document's url starts with the url of the issuer. */ skipIssuerCheck?: boolean; /** * According to rfc6749 it is recommended (but not required) that the auth * server exposes the access_token's life time in seconds. * This is a fallback value for the case this value is not exposed. */ fallbackAccessTokenExpirationTimeInSec?: number; /** * final state sent to issuer is built as follows: * state = nonce + nonceStateSeparator + additional state * Default separator is ';' (encoded %3B). * In rare cases, this character might be forbidden or inconvenient to use by the issuer so it can be customized. */ nonceStateSeparator?: string; /** * Set this to true to use HTTP BASIC auth for AJAX calls */ useHttpBasicAuth?: boolean; /** * The window of time (in seconds) to allow the current time to deviate when validating id_token's iat and exp values. */ clockSkewInSec?: number; /** * Decreases the Expiration time of tokens by this number of seconds */ decreaseExpirationBySec?: number; /** * The interceptors waits this time span if there is no token */ waitForTokenInMsec?: number; /** * Set this to true if you want to use silent refresh together with * code flow. As silent refresh is the only option for refreshing * with implicit flow, you don't need to explicitly turn it on in * this case. */ useSilentRefresh?: any; /** * Code Flow is by defauld used together with PKCI which is also higly recommented. * You can disbale it here by setting this flag to true. * https://tools.ietf.org/html/rfc7636#section-1.1 */ disablePKCE?: boolean; /** * Set this to true to preserve the requested route including query parameters after code flow login. * This setting enables deep linking for the code flow. */ preserveRequestedRoute?: boolean; /** * Allows to disable the timer for the id_token used * for token refresh */ disableIdTokenTimer?: boolean; /** * Blocks other origins requesting a silent refresh */ checkOrigin?: boolean; constructor(json?: Partial<AuthConfig>); /** * This property allows you to override the method that is used to open the login url, * allowing a way for implementations to specify their own method of routing to new * urls. */ openUri?: (uri: string) => void; } /** * Abstraction for crypto algorithms */ declare abstract class HashHandler { abstract calcHash(valueToHash: string, algorithm: string): Promise<string>; } declare class DefaultHashHandler implements HashHandler { calcHash(valueToHash: string, algorithm: string): Promise<string>; toHashString2(byteArray: number[]): string; toHashString(buffer: ArrayBuffer): string; static ɵfac: i0.ɵɵFactoryDeclaration<DefaultHashHandler, never>; static ɵprov: i0.ɵɵInjectableDeclaration<DefaultHashHandler>; } /** * Service for logging in and logging out with * OIDC and OAuth2. Supports implicit flow and * password flow. */ declare class OAuthService extends AuthConfig implements OnDestroy { protected ngZone: NgZone; protected http: HttpClient; protected config: AuthConfig; protected urlHelper: UrlHelperService; protected logger: OAuthLogger; protected crypto: HashHandler; protected dateTimeService: DateTimeProvider; /** * The ValidationHandler used to validate received * id_tokens. */ tokenValidationHandler: ValidationHandler; /** * @internal * Deprecated: use property events instead */ discoveryDocumentLoaded: boolean; /** * @internal * Deprecated: use property events instead */ discoveryDocumentLoaded$: Observable<OidcDiscoveryDoc>; /** * Informs about events, like token_received or token_expires. * See the string enum EventType for a full list of event types. */ events: Observable<OAuthEvent>; /** * The received (passed around) state, when logging * in with implicit flow. */ state?: string; protected eventsSubject: Subject<OAuthEvent>; protected discoveryDocumentLoadedSubject: Subject<OidcDiscoveryDoc>; protected silentRefreshPostMessageEventListener: EventListener; protected grantTypesSupported: Array<string>; protected _storage: OAuthStorage; protected accessTokenTimeoutSubscription: Subscription; protected idTokenTimeoutSubscription: Subscription; protected tokenReceivedSubscription: Subscription; protected automaticRefreshSubscription: Subscription; protected sessionCheckEventListener: EventListener; protected jwksUri: string; protected sessionCheckTimer: any; protected silentRefreshSubject: string; protected inImplicitFlow: boolean; protected saveNoncesInLocalStorage: boolean; private document; constructor(ngZone: NgZone, http: HttpClient, storage: OAuthStorage, tokenValidationHandler: ValidationHandler, config: AuthConfig, urlHelper: UrlHelperService, logger: OAuthLogger, crypto: HashHandler, document: Document, dateTimeService: DateTimeProvider); private checkLocalStorageAccessable; /** * Use this method to configure the service * @param config the configuration */ configure(config: AuthConfig): void; protected configChanged(): void; restartSessionChecksIfStillLoggedIn(): void; protected restartRefreshTimerIfStillLoggedIn(): void; protected setupSessionCheck(): void; /** * Will set up up silent refreshing for when the token is * about to expire. When the user is logged out via this.logOut method, the * silent refreshing will pause and not refresh the tokens until the user is * logged back in via receiving a new token. * @param params Additional parameter to pass * @param listenTo Set up automatic refresh of a specific token type */ setupAutomaticSilentRefresh(params?: object, listenTo?: 'access_token' | 'id_token' | 'any', noPrompt?: boolean): void; protected refreshInternal(params: any, noPrompt: any): Promise<TokenResponse | OAuthEvent>; /** * Convenience method that first calls `loadDiscoveryDocument(...)` and * directly chains using the `then(...)` part of the promise to call * the `tryLogin(...)` method. * * @param options LoginOptions to pass through to `tryLogin(...)` */ loadDiscoveryDocumentAndTryLogin(options?: LoginOptions): Promise<boolean>; /** * Convenience method that first calls `loadDiscoveryDocumentAndTryLogin(...)` * and if then chains to `initLoginFlow()`, but only if there is no valid * IdToken or no valid AccessToken. * * @param options LoginOptions to pass through to `tryLogin(...)` */ loadDiscoveryDocumentAndLogin(options?: LoginOptions & { state?: string; }): Promise<boolean>; protected debug(...args: any[]): void; protected validateUrlFromDiscoveryDocument(url: string): string[]; protected validateUrlForHttps(url: string): boolean; protected assertUrlNotNullAndCorrectProtocol(url: string | undefined, description: string): void; protected validateUrlAgainstIssuer(url: string): boolean; protected setupRefreshTimer(): void; protected setupExpirationTimers(): void; protected setupAccessTokenTimer(): void; protected setupIdTokenTimer(): void; /** * Stops timers for automatic refresh. * To restart it, call setupAutomaticSilentRefresh again. */ stopAutomaticRefresh(): void; protected clearAccessTokenTimer(): void; protected clearIdTokenTimer(): void; protected clearAutomaticRefreshTimer(): void; protected calcTimeout(storedAt: number, expiration: number): number; /** * DEPRECATED. Use a provider for OAuthStorage instead: * * { provide: OAuthStorage, useFactory: oAuthStorageFactory } * export function oAuthStorageFactory(): OAuthStorage { return localStorage; } * Sets a custom storage used to store the received * tokens on client side. By default, the browser's * sessionStorage is used. * @ignore * * @param storage */ setStorage(storage: OAuthStorage): void; /** * Loads the discovery document to configure most * properties of this service. The url of the discovery * document is infered from the issuer's url according * to the OpenId Connect spec. To use another url you * can pass it to optional parameter fullUrl. * * @param fullUrl */ loadDiscoveryDocument(fullUrl?: string): Promise<OAuthSuccessEvent>; protected loadJwks(): Promise<object>; protected validateDiscoveryDocument(doc: OidcDiscoveryDoc): boolean; /** * Uses password flow to exchange userName and password for an * access_token. After receiving the access_token, this method * uses it to query the userinfo endpoint in order to get information * about the user in question. * * When using this, make sure that the property oidc is set to false. * Otherwise, stricter validations take place that make this operation * fail. * * @param userName * @param password * @param headers Optional additional http-headers. */ fetchTokenUsingPasswordFlowAndLoadUserProfile(userName: string, password: string, headers?: HttpHeaders): Promise<object>; /** * Loads the user profile by accessing the user info endpoint defined by OpenId Connect. * * When using this with OAuth2 password flow, make sure that the property oidc is set to false. * Otherwise, stricter validations take place that make this operation fail. */ loadUserProfile(): Promise<object>; /** * Uses password flow to exchange userName and password for an access_token. * @param userName * @param password * @param headers Optional additional http-headers. */ fetchTokenUsingPasswordFlow(userName: string, password: string, headers?: HttpHeaders): Promise<TokenResponse>; /** * Uses a custom grant type to retrieve tokens. * @param grantType Grant type. * @param parameters Parameters to pass. * @param headers Optional additional HTTP headers. */ fetchTokenUsingGrant(grantType: string, parameters: object, headers?: HttpHeaders): Promise<TokenResponse>; /** * Refreshes the token using a refresh_token. * This does not work for implicit flow, b/c * there is no refresh_token in this flow. * A solution for this is provided by the * method silentRefresh. */ refreshToken(): Promise<TokenResponse>; protected removeSilentRefreshEventListener(): void; protected setupSilentRefreshEventListener(): void; /** * Performs a silent refresh for implicit flow. * Use this method to get new tokens when/before * the existing tokens expire. */ silentRefresh(params?: object, noPrompt?: boolean): Promise<OAuthEvent>; /** * This method exists for backwards compatibility. * {@link OAuthService#initLoginFlowInPopup} handles both code * and implicit flows. */ initImplicitFlowInPopup(options?: { height?: number; width?: number; windowRef?: Window; }): Promise<unknown>; initLoginFlowInPopup(options?: { height?: number; width?: number; windowRef?: Window; }): Promise<unknown>; protected calculatePopupFeatures(options: { height?: number; width?: number; }): string; protected processMessageEventMessage(e: MessageEvent): string; protected canPerformSessionCheck(): boolean; protected setupSessionCheckEventListener(): void; protected handleSessionUnchanged(): void; protected handleSessionChange(): void; protected waitForSilentRefreshAfterSessionChange(): void; protected handleSessionError(): void; protected removeSessionCheckEventListener(): void; protected initSessionCheck(): void; protected startSessionCheckTimer(): void; protected stopSessionCheckTimer(): void; checkSession(): void; protected createLoginUrl(state?: string, loginHint?: string, customRedirectUri?: string, noPrompt?: boolean, params?: object): Promise<string>; initImplicitFlowInternal(additionalState?: string, params?: string | object): void; /** * Starts the implicit flow and redirects to user to * the auth servers' login url. * * @param additionalState Optional state that is passed around. * You'll find this state in the property `state` after `tryLogin` logged in the user. * @param params Hash with additional parameter. If it is a string, it is used for the * parameter loginHint (for the sake of compatibility with former versions) */ initImplicitFlow(additionalState?: string, params?: string | object): void; /** * Reset current implicit flow * * @description This method allows resetting the current implict flow in order to be initialized again. */ resetImplicitFlow(): void; protected callOnTokenReceivedIfExists(options: LoginOptions): void; protected storeAccessTokenResponse(accessToken: string, refreshToken: string, expiresIn: number, grantedScopes: string, customParameters?: Map<string, string>): void; /** * Delegates to tryLoginImplicitFlow for the sake of compatability * @param options Optional options. */ tryLogin(options?: LoginOptions): Promise<boolean>; private parseQueryString; tryLoginCodeFlow(options?: LoginOptions): Promise<void>; private saveRequestedRoute; private restoreRequestedRoute; /** * Retrieve the returned auth code from the redirect uri that has been called. * If required also check hash, as we could use hash location strategy. */ private getCodePartsFromUrl; /** * Get token using an intermediate code. Works for the Authorization Code flow. */ private getTokenFromCode; private fetchAndProcessToken; /** * Checks whether there are tokens in the hash fragment * as a result of the implicit flow. These tokens are * parsed, validated and used to sign the user in to the * current client. * * @param options Optional options. */ tryLoginImplicitFlow(options?: LoginOptions): Promise<boolean>; private parseState; protected validateNonce(nonceInState: string): boolean; protected storeIdToken(idToken: ParsedIdToken): void; protected storeSessionState(sessionState: string): void; protected getSessionState(): string; protected handleLoginError(options: LoginOptions, parts: object): void; private getClockSkewInMsec; /** * @ignore */ processIdToken(idToken: string, accessToken: string, skipNonceCheck?: boolean): Promise<ParsedIdToken>; /** * Returns the received claims about the user. */ getIdentityClaims(): Record<string, any>; /** * Returns the granted scopes from the server. */ getGrantedScopes(): object; /** * Returns the current id_token. */ getIdToken(): string; protected padBase64(base64data: any): string; /** * Returns the current access_token. */ getAccessToken(): string; getRefreshToken(): string; /** * Returns the expiration date of the access_token * as milliseconds since 1970. */ getAccessTokenExpiration(): number; protected getAccessTokenStoredAt(): number; protected getIdTokenStoredAt(): number; /** * Returns the expiration date of the id_token * as milliseconds since 1970. */ getIdTokenExpiration(): number; /** * Checkes, whether there is a valid access_token. */ hasValidAccessToken(): boolean; /** * Checks whether there is a valid id_token. */ hasValidIdToken(): boolean; /** * Retrieve a saved custom property of the TokenReponse object. Only if predefined in authconfig. */ getCustomTokenResponseProperty(requestedProperty: string): any; /** * Returns the auth-header that can be used * to transmit the access_token to a service */ authorizationHeader(): string; /** * Removes all tokens and logs the user out. * If a logout url is configured, the user is * redirected to it with optional state parameter. * @param noRedirectToLogoutUrl * @param state */ logOut(): void; logOut(customParameters: boolean | object): void; logOut(noRedirectToLogoutUrl: boolean): void; logOut(noRedirectToLogoutUrl: boolean, state: string): void; /** * @ignore */ createAndSaveNonce(): Promise<string>; /** * @ignore */ ngOnDestroy(): void; protected createNonce(): Promise<string>; protected checkAtHash(params: ValidationParams): Promise<boolean>; protected checkSignature(params: ValidationParams): Promise<any>; /** * Start the implicit flow or the code flow, * depending on your configuration. */ initLoginFlow(additionalState?: string, params?: {}): void; /** * Starts the authorization code flow and redirects to user to * the auth servers login url. */ initCodeFlow(additionalState?: string, params?: {}): void; private initCodeFlowInternal; protected createChallangeVerifierPairForPKCE(): Promise<[ string, string ]>; private extractRecognizedCustomParameters; /** * Revokes the auth token to secure the vulnarability * of the token issued allowing the authorization server to clean * up any security credentials associated with the authorization */ revokeTokenAndLogout(customParameters?: boolean | object, ignoreCorsIssues?: boolean): Promise<any>; /** * Clear location.hash if it's present */ private clearLocationHash; static ɵfac: i0.ɵɵFactoryDeclaration<OAuthService, [null, null, { optional: true; }, { optional: true; }, { optional: true; }, null, null, { optional: true; }, null, null]>; static ɵprov: i0.ɵɵInjectableDeclaration<OAuthService>; } /** * This is just a dummy of the JwksValidationHandler * telling the users that the real one has been moved * to an library of its own, namely angular-oauth2-oidc-utils */ declare class JwksValidationHandler extends NullValidationHandler { constructor(); } declare const AUTH_CONFIG: InjectionToken<AuthConfig>; declare abstract class OAuthResourceServerErrorHandler { abstract handleError(err: HttpResponse<any>): Observable<any>; } declare class OAuthNoopResourceServerErrorHandler implements OAuthResourceServerErrorHandler { handleError(err: HttpResponse<any>): Observable<any>; } declare class DefaultOAuthInterceptor implements HttpInterceptor { private oAuthService; private errorHandler; private moduleConfig; constructor(oAuthService: OAuthService, errorHandler: OAuthResourceServerErrorHandler, moduleConfig: OAuthModuleConfig); private checkUrl; intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>; static ɵfac: i0.ɵɵFactoryDeclaration<DefaultOAuthInterceptor, [null, null, { optional: true; }]>; static ɵprov: i0.ɵɵInjectableDeclaration<DefaultOAuthInterceptor>; } declare function provideOAuthClient(config?: OAuthModuleConfig, validationHandlerClass?: typeof NullValidationHandler): EnvironmentProviders; export { AUTH_CONFIG, AbstractValidationHandler, AuthConfig, DateTimeProvider, DefaultHashHandler, DefaultOAuthInterceptor, HashHandler, JwksValidationHandler, LoginOptions, MemoryStorage, NullValidationHandler, OAuthErrorEvent, OAuthEvent, OAuthInfoEvent, OAuthLogger, OAuthModule, OAuthModuleConfig, OAuthNoopResourceServerErrorHandler, OAuthResourceServerConfig, OAuthResourceServerErrorHandler, OAuthService, OAuthStorage, OAuthSuccessEvent, ReceivedTokens, SystemDateTimeProvider, UrlHelperService, ValidationHandler, provideOAuthClient }; export type { EventType, OidcDiscoveryDoc, ParsedIdToken, TokenResponse, UserInfo, ValidationParams };