Keycloak javascript adapter init with tokens not working?

Viewed 602

I'm trying to use the keycloak js adapter, by using tokens given by Keycloak. https://www.npmjs.com/package/@react-keycloak/web Something like this:

import { ReactKeycloakProvider } from '@react-keycloak/web';
import keycloakClient from './keycloak';
import AuthenticatedApp from './AuthenticatedApp';

const keycloakInitOptions = {
  onLoad: 'check-sso',
  // enableLogging: true,
  token: token,
  refreshToken: refreshToken,
  idToken: idToken,
  checkLoginIframe: false,
  // promiseType: legacy
};

function App() {
  return (
    <ReactKeycloakProvider
      authClient={keycloakClient}
      initOptions={keycloakInitOptions}>
      <AuthenticatedApp />
    </ReactKeycloakProvider>
  );
}

export default App;

But it doesn't seem to use the tokens. If I look at the keycloak object, the tokens are just undefined. Maybe I have misunderstood how to use it? Maybe it's something with the react wrapper that changes how it used. I looked at this https://keycloak.discourse.group/t/automatic-login-to-javascript-client-adapter-with-inital-access-and-refresh-token/1331 and I seem to be doing the same. I have tried without the access token, and without the refresh token to see if it made a difference or not. I tried the promiseType=legacy, but same result.

1 Answers

unless you are looking to use some advanced features, you dont really need to use react-keycloak lib. You can directly use the oficial keycloak.js adapter provided by the server you are talking with.It could even bring you less trouble in the future, when updating versions.

First , install npm i keycloak-js (important that the version of the js file should match the version of your keycloak server)

then in your index.js (or main react bootstrap file)

import Keycloak from 'keycloak-js';

let initOptions = {
url: 'https://yourkeycloakserver/auth', realm: 'somerealm', clientId: 'someclientid', onLoad: 'login-required'}
let keycloak = Keycloak(initOptions);

Then wrap your whole React app inside keycloak's success block

keycloak.init({ onLoad: initOptions.onLoad }).success((auth) => {
  if (!auth) {
      window.location.reload();
  } else {
      console.info("Authenticated");
  }

  localStorage.setItem("token", keycloak.token);
  localStorage.setItem("refresh-token", keycloak.refreshToken);
  
  ReactDOM.render(
 //load your app here when logged in
   <MainContainer/>
  );


setTimeout(() => {
      keycloak.updateToken(70).success((refreshed) => {
          if (refreshed) {
              console.debug('Token refreshed' + refreshed);
          } else {
              console.warn('Token not refreshed, valid for '
                  + Math.round(keycloak.tokenParsed.exp + keycloak.timeSkew - new Date().getTime() / 1000) + ' seconds');
          }
      }).error(() => {
          console.error('Failed to refresh token');
      });

  }, 60000)

}).error(() => {
  console.error("Authenticated Failed");
});
Related