# Class TwinfinitySession<ApplicationStateT>

TwinfinitySession uses the OpenID Connect Protocol to establish a session with Twinfinity's identity provider. Once a TwinfinitySession has been established it can be used to retrieve bearer tokens (rfc6750) and identity tokens.

In order to establish a session the browser is redirected to Twinfinity's identity provider. The state of the page before the redirection is stored by TwinfinitySession using ApplicationState. A custom ApplicationState can be supplied by the user to for instance store routing information or similar. If a custom ApplicationState is not supplied then originalUrlApplicationState is used.

TwinfinitySession automatically refreshes its session with Twinfinity's identity provider. No action from the user of TwinfinitySession should be necessary to keep the session alive.

If the session is terminated then all callbacks registered with TwinfinitySession#registerOnSessionTerminatedCallback are called. TwinfinitySession#reEstablish can then be used to re-establish the session. When TwinfinitySession#reEstablish is called the current application state is stored in the same manner as when establish is called.

#### Type Parameters

- ApplicationStateT

##### Index

### Accessors

recoveredApplicationState

### Methods

disconnect
getAuthorizationHeader
getIdentityToken
reEstablish
registerOnSessionTerminatedCallback
create
establish
establishEmbedded
establishUsingPopup

## Accessors

### recoveredApplicationState

- get recoveredApplicationState(): ApplicationStateT

  An ApplicationStateT that was stored and then recovered from before establish (or reEstablish) was called. Should be used to recover any useful state that might have been lost during the redirection caused by establishing the session, such as query parameters.

  In order to use a ApplicationStateT of your own choosing you need to establish the session by passing a custom instance of ApplicationState to establish.

  #### Returns ApplicationStateT

## Methods

### disconnect

- disconnect(): void

  #### Returns void

### getAuthorizationHeader

- getAuthorizationHeader(): Promise<string>

  Returns an authorization header that can be used to authenticate the user of the current session.

  #### Returns Promise<string>

  #### Throws

  an TwinfinitySessionError if it is not possible to fetch the bearer token, e.g. if the session has been terminated.

  #### Example

      const token = await session.getAuthorizationHeader(); // Returns a string of the form 'Bearer <access token>'

### getIdentityToken

- getIdentityToken(): Promise<IdentityToken>

  Returns the identity token that is associated with user of the current session.

  #### Returns Promise<IdentityToken>

### reEstablish

- reEstablish(): Promise<never>

  Re-establishes the session. This effectively re-initiates the same flow that establish uses.

  Just as when establish is called, the current state of the application is stored. If the TwinfinitySession was created by calling establish without specifying a custom ApplicationState that means that the current URL is stored.

  Note that the returned promise will never resolve, effectively halting the execution of the promise chain.

  #### Returns Promise<never>

  #### Throws

  an TwinfinitySessionError if we're unable to re-establish the session.

### registerOnSessionTerminatedCallback

- registerOnSessionTerminatedCallback(
  callback: Callback<SessionTerminatedEvent>,
  ): void

  The registered callbacks will be called when the session has been terminated. A session is said to have been terminated when it is in such a state that it can not be resumed. When that has happened one needs to call reEstablish to re-establish the session. Note that reEstablish will cause the browser to be redirected.

  #### Parameters

  - callback: Callback<SessionTerminatedEvent>

  #### Returns void

### `Static` create

- create(
  oidcClient: OpenIdConnectClient,
  oidcOptions: OpenIdConnectClientOptions,
  ): TwinfinitySession<undefined>

  #### Parameters

  - oidcClient: OpenIdConnectClient
  - oidcOptions: OpenIdConnectClientOptions

  #### Returns TwinfinitySession<undefined>

### `Static` establish

- establish<ApplicationStateT>(
  options: TwinfinitySessionOptionsWithApplicationState<ApplicationStateT>,
  dependencies?: TwinfinitySessionDependencies,
  ): Promise<TwinfinitySession<ApplicationStateT>>

  Establishes a Twinfinity session using OIDC code flow.

  establish will cause the browser to be redirected to the OpenID Connect provider for authentication on the applications initial load. Once authenticated the OpenID Connect provider will redirect the browser back to the applications URL, but with a few significant differences:

  - The browser will be redirected back to
    - OpenIdConnectClientOptions.redirectUri if it is set, or
    - window.location.href with its query parameters and the fragments stripped.
  - Some new query parameters that has to do with the authentication will have been set by the OpenID Connect provider to the redirect URI, such as `state`, `code` and so on.

  establish will use the authentication related query parameters to setup the session, it will then strip them from the current URL.

  In order to preserve state during the redirection establish will store a state that that can be accessed after the session has been established using the recoveredApplicationState property. By default an OriginalURL object is persisted, and by calling OriginalURL.restoreOriginalUrl on it it is possible to recover the original URL from before the authentication flow began.

  It is also possible to supply an ApplicationState object to establish if you want to persist more or other information, such as routing information or similar.

  It is good practice to establish a session as early as possible in the application, ideally before the rest of the heavy machinery in the application has be instantiated.

  It is also good practice to not store the session as a field in the application, one should instead take care to ensure that it is only referenced in closures if possible. In the specific case of BimApi.create it is safe to pass it directly since we know that BimApi will take care to not leave it exposed.

  #### Type Parameters

  - ApplicationStateT

  #### Parameters

  - options: TwinfinitySessionOptionsWithApplicationState<ApplicationStateT>
  - `Optional` dependencies: TwinfinitySessionDependencies

  #### Returns Promise<TwinfinitySession<ApplicationStateT>>

  #### Throws

  a TwinfinitySessionError if we're unable to establish a session

  #### Example

      // Establish a Twinfinity session
      const session = await TwinfinitySession.establish({
        clientId: '<client-id>',
        openIdProviderUrl: '<idp-url>'
      });
      // Add a listener that will notify you when the session is terminated. The session should
      // typically be automatically refreshed, but it is possible for it to break
      session.registerOnSessionTerminatedCallback(async () => {
        // Let the user know that the session has been terminated, perhaps through a modal window
        const modal = await showSessionTerminatedModal();
        // This will re-establish the session by redirecting the browser the same way as {@link establish} does.
        modal.button.onClick(async () => await session.reEstablish());
      });
      // Restore the original url from before the authentication flow began.
      session.recoveredApplicationState.restoreOriginalUrl();
      // Get the user's id_token
      const identityToken = session.getIdentityToken();
      // Use the session to create an authenticated BimApi instance
      const api = await BimApi.create('viewer', apiUrl, {
           session
      });

- establish(
  options: TwinfinitySessionOptions,
  dependencies?: TwinfinitySessionDependencies,
  ): Promise<TwinfinitySession<OriginalUrl>>

  Establishes a Twinfinity session using OIDC code flow.

  establish will cause the browser to be redirected to the OpenID Connect provider for authentication on the applications initial load. Once authenticated the OpenID Connect provider will redirect the browser back to the applications URL, but with a few significant differences:

  - The browser will be redirected back to
    - OpenIdConnectClientOptions.redirectUri if it is set, or
    - window.location.href with its query parameters and the fragments stripped.
  - Some new query parameters that has to do with the authentication will have been set by the OpenID Connect provider to the redirect URI, such as `state`, `code` and so on.

  establish will use the authentication related query parameters to setup the session, it will then strip them from the current URL.

  In order to preserve state during the redirection establish will store a state that that can be accessed after the session has been established using the recoveredApplicationState property. By default an OriginalURL object is persisted, and by calling OriginalURL.restoreOriginalUrl on it it is possible to recover the original URL from before the authentication flow began.

  It is also possible to supply an ApplicationState object to establish if you want to persist more or other information, such as routing information or similar.

  It is good practice to establish a session as early as possible in the application, ideally before the rest of the heavy machinery in the application has be instantiated.

  It is also good practice to not store the session as a field in the application, one should instead take care to ensure that it is only referenced in closures if possible. In the specific case of BimApi.create it is safe to pass it directly since we know that BimApi will take care to not leave it exposed.

  #### Parameters

  - options: TwinfinitySessionOptions
  - `Optional` dependencies: TwinfinitySessionDependencies

  #### Returns Promise<TwinfinitySession<OriginalUrl>>

  #### Throws

  a TwinfinitySessionError if we're unable to establish a session

  #### Example

      // Establish a Twinfinity session
      const session = await TwinfinitySession.establish({
        clientId: '<client-id>',
        openIdProviderUrl: '<idp-url>'
      });
      // Add a listener that will notify you when the session is terminated. The session should
      // typically be automatically refreshed, but it is possible for it to break
      session.registerOnSessionTerminatedCallback(async () => {
        // Let the user know that the session has been terminated, perhaps through a modal window
        const modal = await showSessionTerminatedModal();
        // This will re-establish the session by redirecting the browser the same way as {@link establish} does.
        modal.button.onClick(async () => await session.reEstablish());
      });
      // Restore the original url from before the authentication flow began.
      session.recoveredApplicationState.restoreOriginalUrl();
      // Get the user's id_token
      const identityToken = session.getIdentityToken();
      // Use the session to create an authenticated BimApi instance
      const api = await BimApi.create('viewer', apiUrl, {
           session
      });

### `Static` establishEmbedded

- establishEmbedded(
  options: TwinfinityEmbeddedSessionLoginOptions,
  dependencies?: TwinfinitySessionDependencies,
  ): Promise<TwinfinitySession<OriginalUrl>>

  Establishes a Twinfinity session using an login flow inside an iframe. This is useful for when users already are logged in since it allows the application to establish a session without redirecting the user away from the application.

  A hidden iframe is created if one is not provided in the options. The iframe will be used to load the login flow from the OpenID Connect provider.

  In cases where the user has to authorize use of third party session cookies a hidden iframe will fail to log in with the error `no_cookie_access`. If a visible iframe is used instead, a button will be created inside the iframe which the user can click to authorize the use of third party cookies. This button will be styled according to the `cookieAccessPromptText` and `cookieAccessPromptStyle` options.

  #### Parameters

  - options: TwinfinityEmbeddedSessionLoginOptions
  - `Optional` dependencies: TwinfinitySessionDependencies

  #### Returns Promise<TwinfinitySession<OriginalUrl>>

  #### Example

      // Establish a Twinfinity session using an embedded login flow
      const embeddedLoginContainer = // Element containing additional information to the user
      const loginFrame = // Iframe that will contain the button if needed
      try {
          twinfinitySession = await TwinfinitySession.establishEmbedded(sessionOptions).catch(async (e) => {
              console.debug('Hidden login failed', e);
              if (e.error === 'no_cookie_access') {
                  embeddedLoginContainer.classList.remove('hidden');
                  return await TwinfinitySession.establishEmbedded({
                      ...sessionOptions,
                      loginFrame: loginFrame,
                      cookieAccessPromptText: 'Allow session cookies',
                      cookieAccessPromptStyle: {
                          backgroundColor: '#303030',
                          color: '#FFFFFF'
                      }
                  });
              } else {
                  throw e;
              }
          });
          console.info('Silent authentication successful');
      } catch (e) {
          console.info('Silent authentication failed, falling back to interactive authentication', e);
      } finally {
          embeddedLoginContainer.classList.add('hidden');
      }

### `Static` establishUsingPopup

- establishUsingPopup(
  options: TwinfinitySessionOptions,
  dependencies?: TwinfinitySessionDependencies,
  width?: number,
  height?: number,
  ): Promise<TwinfinitySession<OriginalUrl>>

  Establishes a Twinfinity session using a popup window. This is useful for when users do not have an active session since it allows the application to establish a session without redirecting the user away from the application.

  A popup window is created and used to load the login flow from the OpenID Connect provider.

  #### Parameters

  - options: TwinfinitySessionOptions
  - `Optional` dependencies: TwinfinitySessionDependencies
  - `Optional` width: number
  - `Optional` height: number

  #### Returns Promise<TwinfinitySession<OriginalUrl>>

  #### Example

      // Establish a Twinfinity session using a popup window
      const session = await TwinfinitySession.establishUsingPopup({
        clientId: '<client-id>',
        openIdProviderUrl: '<idp-url>'
      });