How to re-run Keycloak JavaScript adapter check-sso

116 Views Asked by At

I'm using Keycloak JavaScript adapter in my single page web app. I execute

adapter = new Keycloak({
  url: ENV.APP.KEYCLOAK_URL,
  realm: ENV.APP.KEYCLOAK_REALM,
  clientId: ENV.APP.KEYCLOAK_CLIENT_ID,
});

const keycloak_window = window.open(
  // Documentation at https://www.keycloak.org/docs/latest/securing_apps/#methods
  adapter.createLoginUrl(),
  "_blank",
  "popup=true,width=300,height=300",
);

This starts Keycloak JavaScript adapter and open a new window for the user to provide their credentials. This works as expected.

I have more code to update the single page web app when the authentication is complete but it is missing a way to re-run Keycloak JavaScript adapter's check-sso. How can I re-run the check-sso?

1

There are 1 best solutions below

0
On

You can't use the Keycloak JS adapter in this manner, if you want to sign in a user you will have to call the .login() method, which will redirect the user to Keycloak. Signing in through a separate window is not supported.

Your code should look roughly like this:

const keycloak = new Keycloak({
  url: ENV.APP.KEYCLOAK_URL,
  realm: ENV.APP.KEYCLOAK_REALM,
  clientId: ENV.APP.KEYCLOAK_CLIENT_ID,
});

const authenticated = await keycloak.init({
  onLoad: 'check-sso',
});

if (!authenticated) {
  await keycloak.login();
}

I recommend that you read the Keycloak JS documentation, it should give you a good idea of how things should work.