Keycloak js not executing THEN after init

Viewed 581

I am trying to integrate Keycloak login into my React app and I'm trying to get the JWT from keycloak. Here is the code:

  const [keycloakState, setKeycloakState] = useState<any>();

  const login = () => {
    const keycloak = Keycloak("/keycloak.json");

    keycloak.init({onLoad: 'login-required'}).then(authenticated => {
      console.log('kk', keycloak)
      console.log('at', authenticated)
      setKeycloakState({ keycloak: keycloak, authenticated: authenticated });
    }).catch(err => {
      alert(err);
    });

    console.log('log after')
  }

The login function is triggered when a button is clicked. It redirects properly to keycloak, I can log in and I am properly redirected to the app. The problem is that after the redirect back to the app with proper login the code in the then part of the chain is not executed, and even the 'log after' does not appear in the logs. The catch error part works fine.

Why might this be happening? I have keycloak-js added to my project.

2 Answers

I used to face this problem before. The way that I passed is separating the "init" function and then invoke it later. Here is my example on jsFiddle: 'https://jsfiddle.net/gzq6j3yu/1/'

Our solution was to use the functions onAuthSuccess and onAuthError avaliable on the KeycloakInstance keycloak-js provides. (The documentation around this is a little shaky but you can find them if you check out the source code.) As the names imply these functions get called when an auth attempt is successful or unsuccessful, respectively.

note: in the following snippets this._instance replaces OP's keycloak constant.

Basic code snippet:

import Keycloak from 'keycloak-js';

...

// pulled from a class's init function from a custom Keycloak helper class so won't translate one for one but you get the point.

this._instance = Keycloak(configObject);

this._instance.onAuthSuccess = () => { 
  // code to execute on auth success
};

this._instance.onAuthError = () => {
  // code to execute on auth error
};

this._instance.init(initOptions)

...

We also had a getter to get the token on the KeycloakInstance (or empty string) on the same class. This is an easy way to refer to the token in your code to check if it actually exists, etc. Here's what that'd look like inside the class.

  get token() {
    return this._instance ? this._instance.token : '';
  }

Hope this can help out some folks.

Related