keycloak-angular: Error handling when starting the keycloak

Bug Report or Feature Request

- [ X ] bug report 
- [ ] feature request

Versions.

Angular: 9.0.1 Keycloa and keycloak-jsk: 11.0.2 Keycloak-angular: 8.0.1

Repro steps.

Simple follow the README config steps.

Desired functionality.

I would like to know if there is any way to handle errors when starting the keycloak. When the keycloak server is unavailable, for example. I did several tests and under no circumstances was I able to deal with this scenario, the application simply breaks and nothing happens.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 11
  • Comments: 16

Most upvoted comments

Anyone have a working example of this? This is one of the top hits in Google when searching for error handling during keycloak-angular init (and most of the others eventually land you here). I followed the PRs listed above, and made sure I’m using keycloak-js > 15.0.0:

    "keycloak-angular": "~9.1.0",
    "keycloak-js": "~16.1.1",

and my init code:

export function initializeKeycloak(keycloak: KeycloakService) {
  return () => {
    let storedConfig: any = sessionStorage.getItem('kcc');
    if (storedConfig != null) {
      console.log("Initializing Keycloak client with config: " + storedConfig);
      let keycloakConfig = JSON.parse(storedConfig);

      // Wrapping in a try/catch - if the values provided aren't valid, or
      // the keycloak server isn't available, the init function will bomb out
      // the entire site (entire page will be blank and unusable).
      try {
        let init = keycloak.init({
          config: {
            url: keycloakConfig.url,
            realm: keycloakConfig.realm,
            clientId: keycloakConfig.resource
          },
          initOptions: {
            // onLoad: 'check-sso',
            // silentCheckSsoRedirectUri:
            //   window.location.origin + '/assets/silent-check-sso.html',
            // checkLoginIframe: false
          },
        });
        return init;
      }
      catch (exception) {
        console.error("Keycloak initialization exception: " + JSON.stringify(exception, null, 2));
        return null;
      }
    }
    else {
      console.log("Keycloak config not stored.  No client available.");
      return null;
    }
  }
}

This works fine if the values for the realm/resource/etc are valid. But if they aren’t valid, or the KC server is down, I simply get a timeout error core.js:6498 ERROR {error: 'Timeout when waiting for 3rd party check iframe message.'}. The catch code with console.error() is never reached.

So I have kind of a workaround for this one. Basically adding .catch(() => { /* error handling */ }); after keycloakService.init(... enables the app to run. However keycloak js has a default timeout set to 10s, which means you will have 10s of blank screen, after which it loads. For this you can add messageReceiveTimeout: 1000 to initOptions. That value depends on you infra and will cause initial load take as much if keycloak is down.

If the init fails, you also need to configure guards to disable login redirect.

@gatos-cc i run keycloak-js and run into the same issue.

Using vuejs and trying to implement keycloak login. package.json

"keycloak-js": "^18.0.0"
// keycloakInitOptions 
const keycloakInitOptions = {
  onLoad: "login-required",
  checkLoginIframe: false,
};

const keycloak = new Keycloak(keycloakOptions); // *nothing special* URL, REALM, CLIENT_ID

// basic implementation (for testing)
keycloak
    .init(keycloakInitOptions)
    .then((res) => console.log(res))
    .catch((err) => console.error(err));

works when backend config is valid and server is reachable. As soon as i configure a non responding backend or i shutdown keycloak server the application is blocked an results in a 404 Page. Don’t let me start with when i configure a page which has nothing todo with keycloak (like: google.de, reddit.com, or else) then i get 404 pages from them (makes sense) but some kind of (is the backend a keycloak backend would be highly appriciated)

anyone got a working solution for this issue - i realy thinking of throwing keycloak out of this project

+1 We would like to be able to display our app, but render an error if Keycloak client fails to initialize. I have been unable to find a chain to make it work.

In this case below, the error handler is not even triggered if Keycloak is not responding.

function initializeKeycloak(keycloak: KeycloakService): () => Promise<void> {
  const { keycloakConfig } = environment;
  return async () => {
    try {
      await keycloak.init({
        config: keycloakConfig,
        initOptions: {
          onLoad: 'check-sso',
          enableLogging: true,
          silentCheckSsoRedirectUri:
            window.location.origin + '/assets/silent-check-sso.html',
        },
        loadUserProfileAtStartUp: false
      });
    } catch (e) {
      console.error('Failed to initialize Keycloak', e);
    }
  };
}