ionic-appauth icon indicating copy to clipboard operation
ionic-appauth copied to clipboard

ERROR Error: Uncaught (in promise): Error: AuthConfig Not Defined

Open mraible opened this issue 4 years ago • 1 comments

I have the following code in my auth.service.ts class to fetch the OIDC configuration from a REST endpoint. This works great when my app first loads.

private async addConfig() {
  const scopes = 'openid profile offline_access';
  const redirectUri = this.onDevice() ? 'dev.localhost.ionic:/callback' : window.location.origin + '/implicit/callback';
  const logoutRedirectUri = this.onDevice() ? 'dev.localhost.ionic:/logout' : window.location.origin + '/implicit/callback';
  const AUTH_CONFIG_URI = 'http://localhost:8080/api/auth-info';

  if (await this.storage.getItem(AUTH_CONFIG_URI)) {
    console.log('found in local storage')
    this.authConfig = JSON.parse(await this.storage.getItem(AUTH_CONFIG_URI));
    // await this.storage.removeItem(AUTH_CONFIG_URI);
  } else {
    // try to get the oauth settings from the server
    this.requestor.xhr({ method: 'GET', url: AUTH_CONFIG_URI }).then(
      async (data: any) => {
        this.authConfig = {
          identity_client: data.clientId,
          identity_server: data.issuer,
          redirect_url: redirectUri,
          end_session_redirect_url: logoutRedirectUri,
          scopes,
          usePkce: true,
        };
        await this.storage.setItem(AUTH_CONFIG_URI, JSON.stringify(this.authConfig));
      },
      (error) => {
        console.error('ERROR fetching authentication information, defaulting to Keycloak settings');
        console.error(error);
        this.authConfig = {
          identity_client: 'web_app',
          identity_server: 'http://localhost:9080/auth/realms/jhipster',
          redirect_url: redirectUri,
          end_session_redirect_url: logoutRedirectUri,
          scopes,
          usePkce: true,
        };
      }
    );
  }
}

However, if I log in to my app and drill down into a page, then refresh the browser, I get an error:

found in local storage
ERROR Error: Uncaught (in promise): Error: AuthConfig Not Defined
Error: AuthConfig Not Defined
    at AuthService.push../node_modules/ionic-appauth/lib/ionic-auth.js.IonicAuth.getAuthConfig (ionic-auth.js:107)
    at AuthService.<anonymous> (ionic-auth.js:443)
    at step (ionic-auth.js:33)
    at Object.next (ionic-auth.js:14)
    at ionic-auth.js:8

You'll notice that "found in local storage" is printed before this error. If I move that console.log to after this.authConfig is set, I still get the same order of printout and error.

if (await this.storage.getItem(AUTH_CONFIG_URI)) {
  this.authConfig = JSON.parse(await this.storage.getItem(AUTH_CONFIG_URI));
  console.log('found in local storage');
}

Is there a better way to fetch the OIDC configuration dynamically?

mraible avatar Apr 06 '20 18:04 mraible