### Install angular-oauth2-oidc using npm Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/index This command installs the angular-oauth2-oidc library and saves it as a dependency in your project's package.json file. This is the standard way to add the library to your Angular application. ```bash npm i angular-oauth2-oidc --save ``` -------------------------------- ### Generate Documentation with Compodoc Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/index These commands show how to install Compodoc globally and then use it to generate project documentation. This is useful for developers who want to contribute to the project or understand its internal structure. ```bash npm install -g @compodoc/compodoc npm run docs ``` -------------------------------- ### Angular OAuth Module Setup with forRoot Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/modules/OAuthModule The static `forRoot` method in `angular-oauth-oidc.module.ts` initializes the OAuth module. It accepts an `OAuthModuleConfig` object for configuration and an optional `validationHandlerClass`. This method returns `ModuleWithProviders` containing the `OAuthModule` and necessary providers for OAuth client functionality. ```typescript import { NgModule, ModuleWithProviders } from '@angular/core'; import { CommonModule } from '@angular/common'; import { OAuthModuleConfig } from './oauth-module.config'; import { NullValidationHandler } from './token-validation/null-validation-handler'; import { provideOAuthClient } from './provider'; @NgModule({ imports: [CommonModule], declarations: [], exports: [], }) export class OAuthModule { static forRoot( config: OAuthModuleConfig = null, validationHandlerClass = NullValidationHandler ): ModuleWithProviders { return { ngModule: OAuthModule, providers: [provideOAuthClient(config, validationHandlerClass)], }; } } ``` -------------------------------- ### Configure OAuthService using Constructor - TypeScript Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/additional-documentation/original-config-api This snippet demonstrates how to configure the OAuthService within the AppComponent constructor using the original API. It sets the redirect URI, client ID, scope, and issuer, then loads the discovery document and attempts to log in the user. This is essential for initializing the OAuth flow when the application starts. ```TypeScript @Component({ ... }) export class AppComponent { constructor(private oauthService: OAuthService) { // URL of the SPA to redirect the user to after login this.oauthService.redirectUri = window.location.origin + "/index.html"; // The SPA's id. The SPA is registerd with this id at the auth-server this.oauthService.clientId = "spa-demo"; // set the scope for the permissions the client should request // The first three are defined by OIDC. The 4th is a usecase-specific one this.oauthService.scope = "openid profile email voucher"; // The name of the auth-server that has to be mentioned within the token this.oauthService.issuer = "https://steyer-identity-server.azurewebsites.net/identity"; // Load Discovery Document and then try to login the user this.oauthService.loadDiscoveryDocument().then(() => { // This method just tries to parse the token(s) within the url when // the auth-server redirects the user back to the web-app // It dosn't send the user the the login page this.oauthService.tryLogin(); }); } } ``` -------------------------------- ### Setup OAuthClient with Standalone API (Angular 15+) Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/index Configures the OAuthClient using the standalone API in `main.ts` for Angular 15+ applications. It requires `provideHttpClient` and `provideOAuthClient` from 'angular-oauth2-oidc'. This method is suitable for applications using Standalone Components. ```typescript import { bootstrapApplication } from '@angular/platform-browser'; import { provideHttpClient } from '@angular/common/http'; import { AppComponent } from './app/app.component'; import { provideOAuthClient } from 'angular-oauth2-oidc'; bootstrapApplication(AppComponent, { providers: [ provideHttpClient(), provideOAuthClient() ] }); ``` -------------------------------- ### Setup OAuthClient with Standalone API (Angular 14) Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/index Sets up the OAuthClient for Angular 14 applications using Standalone Components but requiring `HttpClientModule` for HTTP requests. It uses `importProvidersFrom` to include `HttpClientModule` alongside `provideOAuthClient`. ```typescript import { bootstrapApplication } from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app/app.component'; import { provideOAuthClient } from 'angular-oauth2-oidc'; import { importProvidersFrom } from '@angular/core'; bootstrapApplication(AppComponent, { providers: [ importProvidersFrom(HttpClientModule), provideOAuthClient() ] }); ``` -------------------------------- ### Auth0 Configuration for angular-oauth2-oidc Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/additional-documentation/authorization-servers/auth0 Provides an example configuration object for initializing the angular-oauth2-oidc library with Auth0. This includes setting the issuer URL, client ID, redirect URI, scopes, response type, logout URL, and custom query parameters like audience for API authorization. ```typescript import { AuthConfig } from 'angular-oauth2-oidc'; export const authConfig: AuthConfig = { issuer: 'https://dev-g-61sdfs.eu.auth0.com/', // Your app's client id: clientId: 'opHt1Tkt9E9fVQTZPBVF1tHVhjrxvyVX', redirectUri: window.location.origin, scope: 'openid profile email offline_access', responseType: 'code', logoutUrl: 'https://dev-g-61sdfs.eu.auth0.com/v2/logout', customQueryParams: { // Your API's name audience: 'http://www.angular.at/api' }, }; ``` -------------------------------- ### Abstract OAuth Storage Interface in TypeScript Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/classes/LoginOptions Defines an abstract interface for client-side token storage. It specifies methods for getting, removing, and setting items, compatible with standard storage mechanisms like localStorage and sessionStorage. ```typescript export abstract class OAuthStorage { abstract getItem(key: string): string | null; abstract removeItem(key: string): void; abstract setItem(key: string, data: string): void; } ``` -------------------------------- ### Initialize Login Flow (Code or Implicit) Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/index Starts the login process by calling `initLoginFlow`. This method intelligently chooses between the code flow or implicit flow based on the application's current `AuthConfig` settings. ```typescript this.oauthService.initLoginFlow(); ``` -------------------------------- ### Initialize Login Flow (Code or Implicit) Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Initiates the login process. It determines whether to start the 'code' flow or the 'implicit' flow based on the `responseType` configuration. This function serves as a central entry point for initiating OAuth2 authentication. ```typescript /** * Start the implicit flow or the code flow, * depending on your configuration. */ public initLoginFlow(additionalState = '', params = {}): void { if (this.responseType === 'code') { return this.initCodeFlow(additionalState, params); } else { return this.initImplicitFlow(additionalState, params); } } ``` -------------------------------- ### Load Discovery Document and Initiate Login Flow Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService This method first loads the discovery document and attempts to log the user in. If no valid ID or access token is found after this attempt, it initiates the login flow. This is a streamlined approach for ensuring a user is logged in or starting the process if they are not. ```typescript /** * 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(...)` */ public loadDiscoveryDocumentAndLogin( options: LoginOptions & { state?: string } = null ): Promise { options = options || {}; return this.loadDiscoveryDocumentAndTryLogin(options).then(() => { if (!this.hasValidIdToken() || !this.hasValidAccessToken()) { const state = typeof options.state === 'string' ? options.state : ''; this.initLoginFlow(state); return false; } else { return true; } }); } ``` -------------------------------- ### Configure JwksValidationHandler via Dependency Injection Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/additional-documentation/adapt-id_token-validation This example shows how to configure the JwksValidationHandler using Angular's dependency injection system. By providing the ValidationHandler token with JwksValidationHandler as the useClass, the library can automatically inject the validation handler, simplifying setup within your application's module. ```typescript import { ValidationHandler, JwksValidationHandler } from 'angular-oauth2-oidc'; [...] providers: [ { provide: ValidationHandler, useClass: JwksValidationHandler }, ], [...] ``` -------------------------------- ### Dummy JwksValidationHandler in TypeScript Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/classes/JwksValidationHandler This TypeScript class acts as a dummy JwksValidationHandler, informing users that the actual implementation has been relocated to the 'angular-oauth2-oidc-jwks' library. It logs an error message upon instantiation, guiding users on how to install and import the correct handler for OAuth2/OIDC implicit flow. It extends NullValidationHandler and does not provide actual validation logic. ```typescript import { NullValidationHandler } from './null-validation-handler'; const err = `PLEASE READ THIS CAREFULLY: Beginning with angular-oauth2-oidc version 9, the JwksValidationHandler has been moved to an library of its own. If you need it for implementing OAuth2/OIDC **implicit flow**, please install it using npm: npm i angular-oauth2-oidc-jwks --save After that, you can import it into your application: import { JwksValidationHandler } from 'angular-oauth2-oidc-jwks'; Please note, that this dependency is not needed for the **code flow**, which is nowadays the **recommented** one for single page applications. This also results in smaller bundle sizes. `; /** * 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 */ export class JwksValidationHandler extends NullValidationHandler { constructor() { super(); console.error(err); } } ``` -------------------------------- ### tryLogin Options Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/classes/LoginOptions Defines the optional configurations available when calling the tryLogin function. ```APIDOC ## tryLogin Options ### Description Additional options that can be passed to `tryLogin` to customize its behavior. ### Method N/A (Describes an object structure) ### Endpoint N/A ### Parameters #### Properties - **customHashFragment** (string) - Optional - Allows specifying a custom hash fragment for the login process. - **customRedirectUri** (string) - Optional - Allows specifying a custom redirect URI. - **disableNonceCheck** (boolean) - Optional - If true, disables the nonce check during login. - **disableOAuth2StateCheck** (boolean) - Optional - If true, disables the OAuth2 state check during login. - **onLoginError** (function) - Optional - A callback function to be executed when a login error occurs. - **onTokenReceived** (function) - Optional - A callback function to be executed when a token is successfully received. - **preventClearHashAfterLogin** (boolean) - Optional - If true, prevents the hash from being cleared after a successful login. - **validationHandler** (object) - Optional - An object that provides custom validation logic. ``` -------------------------------- ### Login Options Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/interfaces/OidcDiscoveryDoc Additional options that can be passed to the `tryLogin` method for customizing the login process. ```APIDOC ## Class: LoginOptions ### Description Represents additional options that can be passed to the `tryLogin` method to customize the authentication flow. ### Properties - **onTokenReceived** (function) - Deprecated: Use property `events` on `OAuthService` instead. Called after a token has been received and successfully validated. - **validationHandler** (function) - Deprecated: Use property `tokenValidationHandler` on `OAuthService` instead. A hook to validate the received tokens. - **onLoginError** (function) - Deprecated: Use property `events` on `OAuthService` instead. Called when `tryLogin` detects an error message in the hash fragment from the auth server. - **customHashFragment** (string) - A custom hash fragment to be used instead of the actual one. Useful for silent refreshes and popup flows. For code flow, it should be set to a hash symbol followed by the querystring. - **disableOAuth2StateCheck** (boolean) - Set to `true` to disable the OAuth2 state check, a security best practice to prevent attacks. Can be set to `true` when only doing OIDC, as OIDC includes a nonce check. - **disableNonceCheck** (boolean) - Set to `true` to disable the nonce check, used to prevent replay attacks. This flag should never be `true` in production environments. ### Usage Example ```typescript const options: LoginOptions = { customHashFragment: '#custom_token=...', disableOAuth2StateCheck: true }; // Assuming 'oauthService' is an instance of OAuthService oauthService.tryLogin(options); ``` ``` -------------------------------- ### Start Session Check Timer in Angular Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Starts a recurring timer using setInterval to periodically call the checkSession method. This function ensures it runs outside the Angular zone to avoid unnecessary change detection cycles. ```typescript protected startSessionCheckTimer(): void { this.stopSessionCheckTimer(); this.ngZone.runOutsideAngular(() => { this.sessionCheckTimer = setInterval( this.checkSession.bind(this), this.sessionCheckIntervall ); }); } ``` -------------------------------- ### Install JwksValidationHandler for Implicit Flow (npm) Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/index Install the separate 'angular-oauth2-oidc-jwks' package if you need the JwksValidationHandler for implementing the implicit flow. This is a breaking change introduced in version 9 to improve tree shaking. This dependency is not required for the recommended code flow. ```bash npm i angular-oauth2-oidc-jwks --save ``` -------------------------------- ### SystemJS Configuration for angular-oauth2-oidc Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/additional-documentation/using-systemjs This SystemJS configuration snippet demonstrates how to set up the 'angular-oauth2-oidc' library. It specifies the main file, module format, default extension, and maps external dependencies like 'jsrsasign'. The `meta` section is crucial for defining runtime dependencies, ensuring 'jsrsasign' is loaded before 'angular-oauth2-oidc'. ```javascript System.config({ ... meta: { 'angular-oauth2-oidc': { deps: ['jsrsasign'] } } ... }); ``` ```javascript 'angular-oauth2-oidc': { main: 'angular-oauth2-oidc.umd.js', format: 'cjs', defaultExtension: 'js', map: { 'jsrsasign': '/node_modules/jsrsasign/lib/jsrsasign', }, meta: { 'angular-oauth2-oidc': { deps: ['require','jsrsasign'] }, } } ``` -------------------------------- ### GET /getRefreshToken Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Retrieves the current refresh token. ```APIDOC ## GET /getRefreshToken ### Description Returns the current refresh token. ### Method GET ### Endpoint /getRefreshToken ### Response #### Success Response (200) - **string** - The current refresh token. #### Response Example ``` "def..." ``` ``` -------------------------------- ### setupAccessTokenTimer Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Sets up a timer related to the access token's lifecycle. ```APIDOC ## POST /timers/access-token/setup ### Description Initializes and starts a timer that manages the access token. This timer is likely responsible for actions like checking token expiration or initiating silent refreshes. ### Method POST ### Endpoint /timers/access-token/setup ### Parameters None ### Request Example ```json // No request body ``` ### Response #### Success Response (200) Returns void. #### Response Example ```json // No response body ``` ``` -------------------------------- ### setupIdTokenTimer Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Sets up a timer specifically for the ID token. ```APIDOC ## POST /timers/id-token/setup ### Description Initializes and starts a timer related to the ID token. This timer might be responsible for its expiration checks or other lifecycle events. ### Method POST ### Endpoint /timers/id-token/setup ### Parameters None ### Request Example ```json // No request body ``` ### Response #### Success Response (200) Returns void. #### Response Example ```json // No response body ``` ``` -------------------------------- ### GET /getIdToken Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Retrieves the current ID token. ```APIDOC ## GET /getIdToken ### Description Returns the current id_token. ### Method GET ### Endpoint /getIdToken ### Response #### Success Response (200) - **string** - The current ID token. #### Response Example ``` "eyJ..." ``` ``` -------------------------------- ### setupRefreshTimer Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Sets up the timer for handling token refreshes. ```APIDOC ## POST /timers/refresh/setup ### Description Initializes and starts the timer responsible for managing token refreshes. This timer ensures that the application attempts to refresh tokens before they expire, maintaining a seamless user experience. ### Method POST ### Endpoint /timers/refresh/setup ### Parameters None ### Request Example ```json // No request body ``` ### Response #### Success Response (200) Returns void. #### Response Example ```json // No response body ``` ``` -------------------------------- ### GET /getIdentityClaims Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Retrieves the claims about the authenticated user. ```APIDOC ## GET /getIdentityClaims ### Description Returns the received claims about the user. ### Method GET ### Endpoint /getIdentityClaims ### Response #### Success Response (200) - **Record** - An object containing the user's identity claims. #### Response Example ```json { "sub": "1234567890", "name": "John Doe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Configuration Options Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/interfaces/OidcDiscoveryDoc This section details the configuration options available for the OAuthService, including settings for nonce checking, clearing hash fragments, and custom redirect URIs. ```APIDOC ## Configuration Options ### Description This section details the configuration options available for the OAuthService, including settings for nonce checking, clearing hash fragments, and custom redirect URIs. ### Method N/A (Configuration settings) ### Endpoint N/A (Configuration settings) ### Parameters #### Query Parameters - **disableNonceCheck** (boolean) - Optional - If set to true, the nonce check will be disabled. - **preventClearHashAfterLogin** (boolean) - Optional - If set to true, the hash fragment will not be cleared after login. For code flow, this controls removing query string values. - **customRedirectUri** (string) - Optional - Set this for code flow if a custom redirect URI was used when retrieving the code. This is used internally for silent refresh and popup flows. ### Request Example N/A ### Response N/A ``` -------------------------------- ### GET /getAccessToken Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Retrieves the current access token. ```APIDOC ## GET /getAccessToken ### Description Returns the current access_token. ### Method GET ### Endpoint /getAccessToken ### Response #### Success Response (200) - **string** - The current access token. #### Response Example ``` "eyJ..." ``` ``` -------------------------------- ### GET /getIdTokenExpiration Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Retrieves the expiration date of the ID token. ```APIDOC ## GET /getIdTokenExpiration ### Description Returns the expiration date of the id_token as milliseconds since 1970. ### Method GET ### Endpoint /getIdTokenExpiration ### Response #### Success Response (200) - **number** - The expiration time of the ID token in milliseconds since the Unix epoch. #### Response Example ``` 1678886400000 ``` ``` -------------------------------- ### GET /getGrantedScopes Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Retrieves the granted scopes from the authorization server. ```APIDOC ## GET /getGrantedScopes ### Description Returns the granted scopes from the server. ### Method GET ### Endpoint /getGrantedScopes ### Response #### Success Response (200) - **object** - An object containing the granted scopes. #### Response Example ```json { "scopes": ["read", "write"] } ``` ``` -------------------------------- ### Fast SHA256 JS Constructor and Usage Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/classes/HMAC This section details the constructor for the Fast SHA256 JS library, which requires a key. It also outlines the available properties and methods for cryptographic operations. ```APIDOC ## Fast SHA256 JS Class ### Description Provides a fast implementation of the SHA256 hashing algorithm. ### Constructor `constructor(key: Uint8Array)` Initializes a new instance of the FastSHA256 class. #### Parameters - **key** (Uint8Array) - Required - The secret key for the hashing operation. ### Properties #### blockSize - **Type**: `number` - **Default value**: `this.inner.blockSize` - **Description**: The block size of the SHA256 algorithm. #### digestLength - **Type**: `number` - **Default value**: `this.inner.digestLength` - **Description**: The length of the digest (hash output) in bytes. ### Methods #### clean() - **Description**: Clears any internal state. #### digest(message: Uint8Array): Uint8Array - **Description**: Computes the SHA256 digest of the given message. - **Parameters**: - **message** (Uint8Array) - Required - The message to hash. - **Returns**: `Uint8Array` - The computed hash. #### finish(): Uint8Array - **Description**: Finalizes the hashing process and returns the digest. - **Returns**: `Uint8Array` - The final hash digest. #### reset() - **Description**: Resets the internal state of the hasher. #### update(message: Uint8Array): void - **Description**: Updates the internal state with a portion of the message. - **Parameters**: - **message** (Uint8Array) - Required - The message chunk to process. ``` -------------------------------- ### GET /getCustomTokenResponseProperty Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Retrieves a custom property from the token response. ```APIDOC ## GET /getCustomTokenResponseProperty ### Description Retrieve a saved custom property of the TokenReponse object. Only if predefined in authconfig. ### Method GET ### Endpoint /getCustomTokenResponseProperty ### Parameters #### Query Parameters - **requestedProperty** (string) - No - The name of the custom property to retrieve. ### Response #### Success Response (200) - **any** - The value of the requested custom property. #### Response Example ```json { "custom_claim": "some_value" } ``` ``` -------------------------------- ### setupSessionCheck Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Sets up the mechanism for checking the user's session status. ```APIDOC ## POST /session/check/setup ### Description Initializes the session checking functionality. This is responsible for periodically verifying that the user's authentication session is still valid with the identity provider. ### Method POST ### Endpoint /session/check/setup ### Parameters None ### Request Example ```json // No request body ``` ### Response #### Success Response (200) Returns void. #### Response Example ```json // No response body ``` ``` -------------------------------- ### GET /getAccessTokenExpiration Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Retrieves the expiration date of the access token. ```APIDOC ## GET /getAccessTokenExpiration ### Description Returns the expiration date of the access_token as milliseconds since 1970. ### Method GET ### Endpoint /getAccessTokenExpiration ### Response #### Success Response (200) - **number** - The expiration time of the access token in milliseconds since the Unix epoch. #### Response Example ``` 1678886400000 ``` ``` -------------------------------- ### GET /hasValidIdToken Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Checks if a valid ID token is currently available. ```APIDOC ## GET /hasValidIdToken ### Description Checks whether there is a valid id_token. ### Method GET ### Endpoint /hasValidIdToken ### Response #### Success Response (200) - **boolean** - `true` if a valid ID token exists, `false` otherwise. #### Response Example ``` true ``` ``` -------------------------------- ### setupSessionCheckEventListener Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Sets up an event listener for session check events. ```APIDOC ## POST /session/check/event-listener/setup ### Description Sets up an event listener that listens for events related to session checks. This allows the application to react to changes in the user's session status, such as timeouts or invalidations. ### Method POST ### Endpoint /session/check/event-listener/setup ### Parameters None ### Request Example ```json // No request body ``` ### Response #### Success Response (200) Returns void. #### Response Example ```json // No response body ``` ``` -------------------------------- ### GET /hasValidAccessToken Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Checks if a valid access token is currently available. ```APIDOC ## GET /hasValidAccessToken ### Description Checkes, whether there is a valid access_token. ### Method GET ### Endpoint /hasValidAccessToken ### Response #### Success Response (200) - **boolean** - `true` if a valid access token exists, `false` otherwise. #### Response Example ``` true ``` ``` -------------------------------- ### Load Discovery Document and Attempt Login Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/index Configures the `oauthService` with the provided authentication settings and attempts to log the user in based on the discovery document. This is a crucial step during application bootstrapping to manage authentication state. ```typescript this.oauthService.configure(authCodeFlowConfig); this.oauthService.loadDiscoveryDocumentAndTryLogin(); ``` -------------------------------- ### setupExpirationTimers Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Sets up timers to manage token expiration. ```APIDOC ## POST /timers/expiration/setup ### Description Initializes and starts timers that monitor the expiration of authentication tokens. These timers are crucial for ensuring that the application handles token expiration gracefully, potentially by initiating a refresh. ### Method POST ### Endpoint /timers/expiration/setup ### Parameters None ### Request Example ```json // No request body ``` ### Response #### Success Response (200) Returns void. #### Response Example ```json // No response body ``` ``` -------------------------------- ### Import JwksValidationHandler (TypeScript) Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/index Import the JwksValidationHandler from the 'angular-oauth2-oidc-jwks' library after installation. This is necessary for using the implicit flow. Previously, it was imported directly from 'angular-oauth2-oidc'. ```typescript import { JwksValidationHandler } from 'angular-oauth2-oidc-jwks'; ``` -------------------------------- ### Load Discovery Document and Try Login Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService A convenience method that first loads the discovery document and then immediately calls `tryLogin` using the provided `LoginOptions`. This simplifies the process of loading configuration and attempting to log in. ```APIDOC ## POST /oauth-service/loadDiscoveryDocumentAndTryLogin ### Description A convenience method that first calls `loadDiscoveryDocument(...)` and directly chains using the `then(...)` part of the promise to call the `tryLogin(...)` method. ### Method POST ### Endpoint /oauth-service/loadDiscoveryDocumentAndTryLogin ### Parameters #### Request Body - **options** (LoginOptions) - No - `null` - LoginOptions to pass through to `tryLogin(...)`. ### Response #### Success Response (200) - **Promise** - A promise that resolves to `true` if login was successful or already established, `false` otherwise. #### Response Example ```json true ``` ``` -------------------------------- ### Start Session Check Timer in Angular OAuth2 OIDC Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Initiates a timer for checking the user's session status. This method is protected and returns void. ```typescript protected startSessionCheckTimer() ``` -------------------------------- ### Fetch Access Token and User Profile with Password Flow - Angular Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/additional-documentation/using-password-flow Demonstrates fetching an access token using the password flow with provided username and password, followed by loading the user's profile information. It also shows a shorthand method to perform both actions consecutively and accessing user claims. ```typescript this.oauthService.fetchTokenUsingPasswordFlow('max', 'geheim').then((resp) => { // Loading data about the user return this.oauthService.loadUserProfile(); }).then(() => { // Using the loaded user data let claims = this.oAuthService.getIdentityClaims(); if (claims) console.debug('given_name', claims.given_name); }) ``` ```typescript this.oauthService.fetchTokenUsingPasswordFlowAndLoadUserProfile('max', 'geheim').then(() => { let claims = this.oAuthService.getIdentityClaims(); if (claims) console.debug('given_name', claims.given_name); }); ``` -------------------------------- ### Interfaces and Abstract Classes Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/interfaces/OidcDiscoveryDoc This section outlines the interfaces and abstract classes provided by the library for custom implementations of logging and storage, as well as data structures for received tokens and API responses. ```APIDOC ## Interfaces and Abstract Classes ### Description This section outlines the interfaces and abstract classes provided by the library for custom implementations of logging and storage, as well as data structures for received tokens and API responses. ### Method N/A (Interface/Class definitions) ### Endpoint N/A (Interface/Class definitions) ### Parameters N/A ### Request Example N/A ### Response N/A **Key Interfaces and Abstract Classes:** - **OAuthLogger**: An abstract class defining the logging interface, compatible with the `console` object. Allows for custom logging implementations. - **OAuthStorage**: An abstract class defining a simple storage interface, compatible with `localStorage` and `sessionStorage`. Allows for custom storage implementations. - **MemoryStorage**: A concrete implementation of `OAuthStorage` using an in-memory `Map`. - **ReceivedTokens**: Represents the received tokens, state, and parsed claims from the ID token. - **ParsedIdToken**: Represents the parsed and validated ID token, including claims and header information. - **TokenResponse**: Represents the response from the token endpoint according to OpenID Connect Core 1.0 specification. - **UserInfo**: Represents the response from the user info endpoint according to OpenID Connect Core 1.0 specification. - **OidcDiscoveryDoc**: Represents an OpenID Connect discovery document, containing various endpoints and supported features. ``` -------------------------------- ### Validate URL Against Issuer (TypeScript) Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Checks if a given URL starts with the configured issuer's URL, performing a case-insensitive comparison. This is used for strict discovery document validation. ```typescript protected validateUrlAgainstIssuer(url: string) { if (!this.strictDiscoveryDocumentValidation) { return true; } if (!url) { return true; } return url.toLowerCase().startsWith(this.issuer.toLowerCase()); } ``` -------------------------------- ### OpenID Connect Discovery Document Interface Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/classes/OAuthLogger Represents an OpenID Connect discovery document, which provides metadata about the OpenID Provider. ```APIDOC ## OIDC Discovery Document ### Description Represents an OpenID Connect discovery document. ### Endpoint `[GET] /.well-known/openid-configuration` ### Parameters (None) ### Response #### Success Response (200) - **issuer** (string) - The issuer identifier. - **authorization_endpoint** (string) - The authorization endpoint URL. - **token_endpoint** (string) - The token endpoint URL. - **token_endpoint_auth_methods_supported** (string[]) - The authentication methods supported for the token endpoint. - **token_endpoint_auth_signing_alg_values_supported** (string[]) - The signing algorithms supported for the token endpoint. - **userinfo_endpoint** (string) - The user info endpoint URL. - **check_session_iframe** (string) - The check session iframe URL. - **end_session_endpoint** (string) - The end session endpoint URL. - **jwks_uri** (string) - The JSON Web Key Set (JWKS) URI. - **registration_endpoint** (string) - The dynamic client registration endpoint URL. - **scopes_supported** (string[]) - The scopes supported. - **response_types_supported** (string[]) - The response types supported. - **acr_values_supported** (string[]) - The Authentication Context Class Reference (ACR) values supported. - **response_modes_supported** (string[]) - The response modes supported. - **grant_types_supported** (string[]) - The grant types supported. - **subject_types_supported** (string[]) - The subject types supported. - **userinfo_signing_alg_values_supported** (string[]) - The signing algorithms supported for the user info endpoint. - **userinfo_encryption_alg_values_supported** (string[]) - The encryption algorithms supported for the user info endpoint. - **userinfo_encryption_enc_values_supported** (string[]) - The encryption encryption algorithms supported for the user info endpoint. - **id_token_signing_alg_values_supported** (string[]) - The signing algorithms supported for the ID token. - **id_token_encryption_alg_values_supported** (string[]) - The encryption algorithms supported for the ID token. - **id_token_encryption_enc_values_supported** (string[]) - The encryption encryption algorithms supported for the ID token. - **request_object_signing_alg_values_supported** (string[]) - The signing algorithms supported for request objects. - **display_values_supported** (string[]) - The display values supported. - **claim_types_supported** (string[]) - The claim types supported. - **claims_supported** (string[]) - The claims supported. - **claims_parameter_supported** (boolean) - Whether the claims parameter is supported. - **service_documentation** (string) - A URL to the service documentation. - **ui_locales_supported** (string[]) - The UI locales supported. - **revocation_endpoint** (string) - The revocation endpoint URL. #### Response Example ```json { "issuer": "https://accounts.google.com", "authorization_endpoint": "https://accounts.google.com/o/oauth2/v2/auth", "token_endpoint": "https://oauth2.googleapis.com/token", "token_endpoint_auth_methods_supported": [ "client_secret_post", "client_secret_basic" ], "jwks_uri": "https://www.googleapis.com/oauth2/v3/certs", "userinfo_endpoint": "https://www.googleapis.com/oauth2/v3/userinfo", "scopes_supported": [ "openid", "email", "profile" ], "response_types_supported": [ "code", "token", "id_token", "code token", "code id_token", "token id_token", "code token id_token", "none" ], "claims_supported": [ "sub", "name", "given_name", "family_name", "email", "email_verified", "picture" ], "grant_types_supported": [ "authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code", "urn:ietf:params:oauth:grant-type:jwt-bearer" ] } ``` ``` -------------------------------- ### Setup Token Expiration Timers (TypeScript) Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Configures timers to trigger events when access tokens or ID tokens expire. It checks for valid tokens and uses `setTimeout` within `runOutsideAngular` for performance. ```typescript protected setupExpirationTimers(): void { if (this.hasValidAccessToken()) { this.setupAccessTokenTimer(); } if (!this.disableIdTokenTimer && this.hasValidIdToken()) { this.setupIdTokenTimer(); } } protected setupAccessTokenTimer(): void { const expiration = this.getAccessTokenExpiration(); const storedAt = this.getAccessTokenStoredAt(); const timeout = this.calcTimeout(storedAt, expiration); this.ngZone.runOutsideAngular(() => { this.accessTokenTimeoutSubscription = of( new OAuthInfoEvent('token_expires', 'access_token') ) .pipe(delay(timeout)) .subscribe((e) => { this.ngZone.run(() => { this.eventsSubject.next(e); }); }); }); } protected setupIdTokenTimer(): void { const expiration = this.getIdTokenExpiration(); const storedAt = this.getIdTokenStoredAt(); const timeout = this.calcTimeout(storedAt, expiration); this.ngZone.runOutsideAngular(() => { this.idTokenTimeoutSubscription = of( new OAuthInfoEvent('token_expires', 'id_token') ) .pipe(delay(timeout)) .subscribe((e) => { this.ngZone.run(() => { this.eventsSubject.next(e); }); }); }); } ``` -------------------------------- ### Fast SHA-256 Hashing Utilities Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/miscellaneous/functions Provides low-level functions for SHA-256 hashing, including HMAC and PBKDF2. ```APIDOC ## fillBuffer ### Description Fills a buffer with data, potentially using HMAC. ### Method `fillBuffer(buffer: Uint8Array, hmac: HMAC, info: any, counter: Uint8Array): void` ### Parameters #### Path Parameters - **buffer** (Uint8Array) - Required - The buffer to fill. - **hmac** (HMAC) - Required - The HMAC algorithm instance. - **info** (any) - Required - Additional information or context. - **counter** (Uint8Array) - Required - The counter bytes. ### Request Example ```javascript // Example usage (HMAC and info would be defined elsewhere) const buffer = new Uint8Array(64); const hmacInstance = createHMAC('sha256'); // Hypothetical HMAC creation const infoData = "some context"; const counterBytes = new Uint8Array([0, 0, 0, 1]); fillBuffer(buffer, hmacInstance, infoData, counterBytes); ``` ## hash ### Description Computes the SHA-256 hash of the given data. ### Method `hash(data: Uint8Array): Uint8Array` ### Parameters #### Path Parameters - **data** (Uint8Array) - Required - The input data to hash. ### Request Example ```javascript const dataToHash = new TextEncoder().encode("hello world"); const hashedData = hash(dataToHash); ``` ### Response #### Success Response (200) - **hashResult** (Uint8Array) - The resulting SHA-256 hash. #### Response Example ```json { "hashResult": [ ... byte array ... ] } ``` ## hashBlocks ### Description Processes blocks of data for hashing. ### Method `hashBlocks(w: Int32Array, v: Int32Array, p: Uint8Array, pos: number, len: number): number` ### Parameters #### Path Parameters - **w** (Int32Array) - Required - Internal state array. - **v** (Int32Array) - Required - Internal state array. - **p** (Uint8Array) - Required - The data block to process. - **pos** (number) - Required - The starting position in the data block. - **len** (number) - Required - The length of data to process. ### Response #### Success Response (200) - **processedBytes** (number) - The number of bytes processed. #### Response Example ```json { "processedBytes": 64 } ``` ## hkdf ### Description Key derivation function (HKDF) based on SHA-256. ### Method `hkdf(key: Uint8Array, salt: Uint8Array, info?: Uint8Array, length: number = 32): Uint8Array` ### Parameters #### Path Parameters - **key** (Uint8Array) - Required - The input key. - **salt** (Uint8Array) - Required - The salt. - **info** (Uint8Array) - Optional - Context information. - **length** (number) - Optional - The desired length of the derived key (defaults to 32). ### Request Example ```javascript const inputKey = new Uint8Array([1, 2, 3]); const saltValue = new Uint8Array([4, 5, 6]); const derivedKey = hkdf(inputKey, saltValue, undefined, 16); ``` ### Response #### Success Response (200) - **derivedKey** (Uint8Array) - The derived key material. #### Response Example ```json { "derivedKey": [ ... byte array ... ] } ``` ## hmac ### Description Computes the HMAC-SHA256 of the given data with a key. ### Method `hmac(key: Uint8Array, data: Uint8Array): Uint8Array` ### Parameters #### Path Parameters - **key** (Uint8Array) - Required - The secret key. - **data** (Uint8Array) - Required - The input data to hash. ### Request Example ```javascript const secretKey = new Uint8Array([10, 20, 30]); const message = new TextEncoder().encode("test message"); const hmacResult = hmac(secretKey, message); ``` ### Response #### Success Response (200) - **hmacResult** (Uint8Array) - The resulting HMAC-SHA256 hash. #### Response Example ```json { "hmacResult": [ ... byte array ... ] } ``` ## pbkdf2 ### Description Password-Based Key Derivation Function 2 (PBKDF2) using HMAC-SHA256. ### Method `pbkdf2(password: Uint8Array, salt: Uint8Array, iterations: number, dkLen: number): Uint8Array` ### Parameters #### Path Parameters - **password** (Uint8Array) - Required - The password. - **salt** (Uint8Array) - Required - The salt. - **iterations** (number) - Required - The number of iterations. - **dkLen** (number) - Required - The desired length of the derived key. ### Request Example ```javascript const userPassword = new TextEncoder().encode("mysecretpassword"); const saltBytes = new Uint8Array([9, 8, 7]); const derivedKeyMaterial = pbkdf2(userPassword, saltBytes, 10000, 32); ``` ### Response #### Success Response (200) - **derivedKeyMaterial** (Uint8Array) - The derived key material. #### Response Example ```json { "derivedKeyMaterial": [ ... byte array ... ] } ``` ``` -------------------------------- ### Initialize Session Check Mechanism Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/injectables/OAuthService Initializes the session checking mechanism by creating and appending an iframe to the DOM. It sets up an event listener for messages from the iframe and starts a timer to periodically check the session status. ```typescript protected initSessionCheck(): void { if (!this.canPerformSessionCheck()) { return; } const existingIframe = this.document.getElementById( this.sessionCheckIFrameName ); if (existingIframe) { this.document.body.removeChild(existingIframe); } const iframe = this.document.createElement('iframe'); iframe.id = this.sessionCheckIFrameName; this.setupSessionCheckEventListener(); const url = this.sessionCheckIFrameUrl; iframe.setAttribute('src', url); iframe.style.display = 'none'; this.document.body.appendChild(iframe); this.startSessionCheckTimer(); } ``` -------------------------------- ### Logging Interface Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/classes/OAuthLogger This section details the abstract methods available in the logging interface used by the OAuthService. These methods allow for different levels of logging, compatible with the browser's console object. ```APIDOC ## Logging Interface ### Description 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. ### Methods * **debug**(message?: any, ...optionalParams: any[]): void Logs a debug message. * **error**(message?: any, ...optionalParams: any[]): void Logs an error message. * **info**(message?: any, ...optionalParams: any[]): void Logs an informational message. * **log**(message?: any, ...optionalParams: any[]): void Logs a general message. * **warn**(message?: any, ...optionalParams: any[]): void Logs a warning message. ``` -------------------------------- ### SHA-256 Hash Class and Methods Source: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/classes/HMAC This section describes the `Hash` class, which implements the SHA-256 algorithm. It includes details on how to initialize, reset, update, and finalize the hash computation. ```APIDOC ## SHA-256 Hash Class This class provides an implementation of the SHA-256 cryptographic hash function. ### Constructor Initializes a new instance of the `Hash` class. ### Methods #### `reset()` * **Description**: Resets the hash state, allowing the instance to be reused for hashing new data. * **Returns**: `this` (the `Hash` instance for chaining). #### `clean()` * **Description**: Cleans internal buffers and re-initializes the hash state. This method clears any buffered data and resets the internal state to its initial values. * **Returns**: `void` #### `update(data: Uint8Array)` * **Description**: Updates the hash state with the provided data. This method can be called multiple times to hash data in chunks. * **Parameters**: * **data** (`Uint8Array`) - Required - The data to be included in the hash computation. * **Returns**: `this` (the `Hash` instance for chaining). #### `digest()` * **Description**: Computes and returns the final hash digest as a `Uint8Array`. After calling `digest()`, the hash instance is typically finalized and cannot be updated further without resetting. * **Returns**: `Uint8Array` - The computed SHA-256 hash digest. #### `finish(out: Uint8Array)` * **Description**: This method appears to be an internal or complementary method for finalizing the hash, potentially writing the final digest to an output buffer. Its exact usage might be specific to internal operations. * **Parameters**: * **out** (`Uint8Array`) - Required - The buffer to write the final hash digest into. * **Returns**: `void` ### Constants * **`digestLength`**: `32` (The length of the SHA-256 hash digest in bytes). * **`blockSize`**: `64` (The block size of the SHA-256 algorithm in bytes). ```