@asgardeo/browser
Version: 
Browser-specific implementation of Asgardeo JavaScript SDK.
652 lines (651 loc) • 22.9 kB
TypeScript
/**
 * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
import { AuthClientConfig, IsomorphicCrypto, TokenExchangeRequestConfig, StorageManager, IdToken, OIDCEndpoints, User } from '@asgardeo/javascript';
import { Hooks } from './constants';
import { AuthenticationHelper } from './helpers';
import { HttpClientInstance } from './http-client';
import { AuthSPAClientConfig, LegacyConfig as Config, HttpRequestConfig, HttpResponse, MainThreadClientConfig, MainThreadClientInterface, SignInConfig, SignOutError, WebWorkerClientConfig, WebWorkerClientInterface } from './models';
import { BrowserStorage } from './models/storage';
/**
 * This class provides the necessary methods to implement authentication in a Single Page Application.
 *
 * @export
 * @class AsgardeoSPAClient
 */
export declare class AsgardeoSPAClient {
    protected static _instances: Map<number, AsgardeoSPAClient>;
    protected _client: WebWorkerClientInterface | MainThreadClientInterface | undefined;
    protected _storage: BrowserStorage | undefined;
    protected _authHelper: typeof AuthenticationHelper;
    protected _worker: new () => Worker;
    protected _initialized: boolean;
    protected _startedInitialize: boolean;
    protected _onSignInCallback: (response: User) => void;
    protected _onSignOutCallback: () => void;
    protected _onSignOutFailedCallback: (error: SignOutError) => void;
    protected _onEndUserSession: (response: any) => void;
    protected _onInitialize: (response: boolean) => void;
    protected _onCustomGrant: Map<string, (response: any) => void>;
    protected _instanceID: number;
    protected constructor(id: number);
    instantiateAuthHelper(authHelper?: typeof AuthenticationHelper): void;
    instantiateWorker(worker: new () => Worker): void;
    /**
     * This method specifies if the `AsgardeoSPAClient` has been initialized or not.
     *
     * @return {Promise<boolean>} - Resolves to `true` if the client has been initialized.
     *
     * @memberof AsgardeoSPAClient
     *
     * @private
     */
    isInitialized(): Promise<boolean>;
    /**
     * This method checks if the SDK is initialized and the user is authenticated.
     *
     * @param validateAuthentication - should user's authenticated status be checked as part of validation
     *
     * @return {Promise<boolean>} - A Promise that resolves with `true` if the SDK is initialized and the
     * user is authenticated.
     *
     * @memberof AsgardeoSPAClient
     *
     * @private
     */
    private _validateMethod;
    /**
     * This method returns the instance of the singleton class.
     * If an ID is provided, it will return the instance with the given ID.
     * If no ID is provided, it will return the default instance value 0.
     *
     * @return {AsgardeoSPAClient} - Returns the instance of the singleton class.
     *
     * @example
     * ```
     * const auth = AsgardeoSPAClient.getInstance();
     * ```
     *
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#getinstance
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    static getInstance(id?: number): AsgardeoSPAClient | undefined;
    /**
     * This method initializes the `AsgardeoSPAClient` instance.
     *
     * @param {ConfigInterface} config The config object to initialize with.
     *
     * @return {Promise<boolean>} - Resolves to `true` if initialization is successful.
     *
     * @example
     * ```
     * auth.initialize({
     *     afterSignInUrl: "http://localhost:3000/sign-in",
     *     clientId: "client ID",
     *     baseUrl: "https://api.asgardeo.io"
     * });
     * ```
     *
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#initialize
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    initialize(config: AuthSPAClientConfig, authHelper?: typeof AuthenticationHelper, workerFile?: new () => Worker): Promise<boolean>;
    /**
     * This method returns a Promise that resolves with the basic user information obtained from the ID token.
     *
     * @return {Promise<User>} - A promise that resolves with the user information.
     *
     * @example
     * ```
     * auth.getUser().then((response) => {
     *    // console.log(response);
     * }).catch((error) => {
     *    // console.error(error);
     * });
     * ```
     *
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#getuserinfo
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    getUser(): Promise<User | undefined>;
    /**
     * This method initiates the authentication flow. This should be called twice.
     *  1. To initiate the authentication flow.
     *  2. To obtain the access token after getting the authorization code.
     *
     * To satisfy the second condition, one of the two strategies mentioned below can be used:
     *  1. Redirect the user back to the same login page that initiated the authentication flow.
     *  2. Call the `signIn()` method in the page the user is redirected to after authentication.
     *
     * **To fire a callback function after signing in, use the `on()` method.**
     * **To learn more about the `on()` method:**
     * @see {@link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#on}
     *
     * @param {SignInConfig} config - The sign-in config.
     * The `SignInConfig` object has these two attributes in addition to any custom key-value pairs.
     *  1. fidp - Specifies the FIDP parameter that is used to take the user directly to an IdP login page.
     *  2. forceInit: Specifies if the OIDC Provider Meta Data should be loaded again from the `well-known`
     * endpoint.
     *  3. Any other parameters that should be appended to the authorization request.
     * @param {string} authorizationCode - The authorization code. (Optional)
     * @param {string} sessionState - The session state. (Optional)
     * @param {string} state - The state. (Optional)
     *
     * @return {Promise<User>} - A promise that resolves with the user information.
     *
     * @example
     * ```
     * auth.signIn();
     * ```
     *
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#signin
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    signIn(config?: SignInConfig, authorizationCode?: string, sessionState?: string, state?: string, tokenRequestConfig?: {
        params: Record<string, unknown>;
    }): Promise<User | undefined>;
    /**
     * This method allows you to sign in silently.
     * First, this method sends a prompt none request to see if there is an active user session in the identity server.
     * If there is one, then it requests the access token and stores it. Else, it returns false.
     *
     * If this method is to be called on page load and the `signIn` method is also to be called on page load,
     * then it is advisable to call this method after the `signIn` call.
     *
     * @return {Promise<User | boolean>} - A Promise that resolves with the user information after signing in
     * or with `false` if the user is not signed in.
     *
     * @example
     *```
     * auth.signInSilently()
     *```
     */
    signInSilently(additionalParams?: Record<string, string | boolean>, tokenRequestConfig?: {
        params: Record<string, unknown>;
    }): Promise<User | boolean | undefined>;
    /**
     * This method initiates the sign-out flow.
     *
     * **To fire a callback function after signing out, use the `on()` method.**
     * **To learn more about the `on()` method:**
     * @see {@link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#on}
     *
     * @return {Promise<boolean>} - Returns a promise that resolves with `true` if sign out is successful.
     *
     * @example
     * ```
     * auth.signOut();
     * ```
     *
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#signout
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    signOut(): Promise<boolean>;
    /**
     * This method sends an API request to a protected endpoint.
     * The access token is automatically attached to the header of the request.
     * This is the only way by which protected endpoints can be accessed
     * when the web worker is used to store session information.
     *
     * @param {HttpRequestConfig} config -  The config object containing attributes necessary to send a request.
     *
     * @return {Promise<HttpResponse>} - Returns a Promise that resolves with the response to the request.
     *
     * @example
     * ```
     *  const requestConfig = {
     *      headers: {
     *          "Accept": "application/json",
     *          "Access-Control-Allow-Origin": "https://api.asgardeo.io/myaccount",
     *          "Content-Type": "application/scim+json"
     *      },
     *      method: "GET",
     *      url: "https://api.asgardeo.io/scim2/me"
     *  };
     *
     *  return auth.httpRequest(requestConfig)
     *     .then((response) => {
     *           // console.log(response);
     *      })
     *      .catch((error) => {
     *           // console.error(error);
     *      });
     * ```
     *
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#httprequest
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    httpRequest(config: HttpRequestConfig): Promise<HttpResponse | undefined>;
    /**
     * This method sends multiple API requests to a protected endpoint.
     * The access token is automatically attached to the header of the request.
     * This is the only way by which multiple requests can be sent to protected endpoints
     * when the web worker is used to store session information.
     *
     * @param {HttpRequestConfig[]} config -  The config object containing attributes necessary to send a request.
     *
     * @return {Promise<HttpResponse[]>} - Returns a Promise that resolves with the responses to the requests.
     *
     * @example
     * ```
     *  const requestConfig = {
     *      headers: {
     *          "Accept": "application/json",
     *          "Content-Type": "application/scim+json"
     *      },
     *      method: "GET",
     *      url: "https://api.asgardeo.io/scim2/me"
     *  };
     *
     *  const requestConfig2 = {
     *      headers: {
     *          "Accept": "application/json",
     *          "Content-Type": "application/scim+json"
     *      },
     *      method: "GET",
     *      url: "https://api.asgardeo.io/scim2/me"
     *  };
     *
     *  return auth.httpRequest([requestConfig, requestConfig2])
     *     .then((responses) => {
     *           response.forEach((response)=>{
     *              // console.log(response);
     *           });
     *      })
     *      .catch((error) => {
     *           // console.error(error);
     *      });
     * ```
     *
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#httprequestall
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    httpRequestAll(config: HttpRequestConfig[]): Promise<HttpResponse[] | undefined>;
    /**
     * This method allows you to send a request with a custom grant.
     *
     * @param {CustomGrantRequestParams} config - The request parameters.
     *
     * @return {Promise<HttpResponse<any> | SignInResponse>} - A Promise that resolves with
     * the value returned by the custom grant request.
     *
     * @example
     * ```
     * auth.customGrant({
     *   attachToken: false,
     *   data: {
     *       client_id: "{{clientId}}",
     *       grant_type: "account_switch",
     *       scope: "{{scope}}",
     *       token: "{{token}}",
     *   },
     *   id: "account-switch",
     *   returnResponse: true,
     *   returnsSession: true,
     *   signInRequired: true
     * });
     * ```
     *
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#customgrant
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    exchangeToken(config: TokenExchangeRequestConfig): Promise<Response | User | undefined>;
    /**
     * This method ends a user session. The access token is revoked and the session information is destroyed.
     *
     * **To fire a callback function after ending user session, use the `on()` method.**
     * **To learn more about the `on()` method:**
     * @see {@link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#on}
     *
     * @return {Promise<boolean>} - A promise that resolves with `true` if the process is successful.
     *
     * @example
     * ```
     * auth.endUserSession();
     * ```
     *
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#endusersession
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    revokeAccessToken(): Promise<boolean | undefined>;
    /**
     * This method returns a Promise that resolves with an object containing the service endpoints.
     *
     * @return {Promise<ServiceResourcesType} - A Promise that resolves with an object containing the service endpoints.
     *
     * @example
     * ```
     * auth.getServiceEndpoints().then((endpoints) => {
     *      // console.log(endpoints);
     *  }).error((error) => {
     *      // console.error(error);
     *  });
     * ```
     *
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#getserviceendpoints
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    getOpenIDProviderEndpoints(): Promise<OIDCEndpoints | undefined>;
    /**
     * This methods returns the Axios http client.
     *
     * @return {HttpClientInstance} - The Axios HTTP client.
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    getHttpClient(): HttpClientInstance;
    /**
     * This method decodes the payload of the id token and returns it.
     *
     * @return {Promise<DecodedIdTokenPayloadInterface>} - A Promise that resolves with
     * the decoded payload of the id token.
     *
     * @example
     * ```
     * auth.getDecodedIdToken().then((response)=>{
     *     // console.log(response);
     * }).catch((error)=>{
     *     // console.error(error);
     * });
     * ```
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#getdecodedidtoken
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    getDecodedIdToken(sessionId?: string): Promise<IdToken | undefined>;
    /**
     * This method returns the IsomorphicCrypto instance.
     *
     * @return {Promise<DecodedIdTokenPayloadInterface>} - A Promise that resolves with
     * the IsomorphicCrypto instance.
     *
     * @example
     * ```
     * auth.getCrypto().then((response)=>{
     *     // console.log(response);
     * }).catch((error)=>{
     *     // console.error(error);
     * });
     * ```
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#getCrypto
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    getCrypto(): Promise<IsomorphicCrypto | undefined>;
    /**
     * This method return the ID token.
     *
     * @return {Promise<string>} - A Promise that resolves with the ID token.
     *
     * @example
     * ```
     * const idToken = await auth.getIdToken();
     * ```
     *
     * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getIdToken
     *
     * @memberof AsgardeoAuthClient
     *
     * @preserve
     */
    getIdToken(): Promise<string | undefined>;
    /**
     * This method return a Promise that resolves with the access token.
     *
     * **This method will not return the access token if the storage type is set to `webWorker`.**
     *
     * @return {Promise<string>} - A Promise that resolves with the access token.
     *
     * @example
     * ```
     *   auth.getAccessToken().then((token) => {
     *       // console.log(token);
     *   }).catch((error) => {
     *       // console.error(error);
     *   });
     * ```
     *
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#getaccesstoken
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    getAccessToken(sessionId?: string): Promise<string>;
    /**
     * This method return a Promise that resolves with the idp access token.
     *
     * **This method will not return the access token if the storage type is set to `webWorker`.**
     *
     * @return {Promise<string>} - A Promise that resolves with the idp access token.
     *
     * @example
     * ```
     *   auth.getIDPAccessToken().then((token) => {
     *       // console.log(token);
     *   }).catch((error) => {
     *       // console.error(error);
     *   });
     * ```
     *
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#getaccesstoken
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    getIDPAccessToken(): Promise<string>;
    /**
     * This method return a Promise that resolves with the data layer object.
     *
     * **This method will not return the data layer object, if the storage type is set to `webWorker`.**
     *
     * @return {Promise<string>} - A Promise that resolves with the data layer object.
     *
     * @example
     * ```
     *   auth.getStorageManager().then((dataLayer) => {
     *       // console.log(dataLayer);
     *   }).catch((error) => {
     *       // console.error(error);
     *   });
     * ```
     *
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#getdatalayer
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    getStorageManager(): Promise<StorageManager<MainThreadClientConfig>>;
    /**
     * This method return a Promise that resolves with the config data stored in the storage.
     *
     * @return - A Promise that resolves with the config data.
     *
     * @example
     * ```
     * auth.getConfigData().then((configData) => {
     *     // console.log(configData);
     * }).catch((error) => {
     *    // console.error(error);
     * });
     * ```
     *
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/main#getConfigData
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    getConfigData(): Promise<AuthClientConfig<MainThreadClientConfig> | AuthClientConfig<WebWorkerClientConfig> | undefined>;
    /**
     * This method refreshes the access token.
     *
     * @return {TokenResponseInterface} - A Promise that resolves with an object containing
     * information about the refreshed access token.
     *
     * @example
     * ```
     * auth.refreshToken().then((response)=>{
     *      // console.log(response);
     * }).catch((error)=>{
     *      // console.error(error);
     * });
     * ```
     *
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#refreshtoken
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    refreshAccessToken(): Promise<User | undefined>;
    /**
     * This method specifies if the user is authenticated or not.
     *
     * @return {Promise<boolean>} - A Promise that resolves with `true` if the user is authenticated.
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    isSignedIn(): Promise<boolean | undefined>;
    /**
     * This method specifies if there is an active session in the browser or not.
     *
     * @return {Promise<boolean>} - A Promise that resolves with `true` if there is a session.
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    isSessionActive(): Promise<boolean | undefined>;
    /**
     * This method attaches a callback function to an event hook that fires the callback when the event happens.
     *
     * @param {Hooks.CustomGrant} hook - The name of the hook.
     * @param {(response?: any) => void} callback - The callback function.
     * @param {string} id (optional) - The id of the hook. This is used when multiple custom grants are used.
     *
     * @example
     * ```
     * auth.on("sign-in", (response)=>{
     *      // console.log(response);
     * });
     * ```
     *
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#on
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    on(hook: Hooks.CustomGrant, callback: (response?: any) => void, id: string): Promise<void>;
    on(hook: Exclude<Hooks, Hooks.CustomGrant>, callback: (response?: any) => void): Promise<void>;
    /**
     * This method enables callback functions attached to the http client.
     *
     * @return {Promise<boolean>} - A promise that resolves with True.
     *
     * @example
     * ```
     * auth.enableHttpHandler();
     * ```
     *
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#enableHttpHandler
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    enableHttpHandler(): Promise<boolean | undefined>;
    /**
     * This method disables callback functions attached to the http client.
     *
     * @return {Promise<boolean>} - A promise that resolves with True.
     *
     * @example
     * ```
     * auth.disableHttpHandler();
     * ```
     *
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master#disableHttpHandler
     *
     * @memberof AsgardeoSPAClient
     *
     * @preserve
     */
    disableHttpHandler(): Promise<boolean | undefined>;
    /**
     * This method updates the configuration that was passed into the constructor when instantiating this class.
     *
     * @param {Partial<AuthClientConfig<T>>} config - A config object to update the SDK configurations with.
     *
     * @example
     * ```
     * const config = {
     *     afterSignInUrl: "http://localhost:3000/sign-in",
     *     clientId: "client ID",
     *     baseUrl: "https://api.asgardeo.io"
     * }
     * const auth.reInitialize(config);
     * ```
     * @link https://github.com/asgardeo/asgardeo-auth-spa-sdk/tree/master/lib#reInitialize
     *
     * @memberof AsgardeoAuthClient
     *
     * @preserve
     */
    reInitialize(config: Partial<AuthClientConfig<Config>>): Promise<void>;
}