React app can't login in Keycloak when token expires, infinite loop, refresh token error

Viewed 1783

I use Keycloak to authenticate user in my React app with keycloak-js and @react-keycloak/web libs.

When I start the app it redirects me to keycloak login page and then back after login/password are entered.

I get tokens: access, refresh etc., and set it to cookies.

But then, when access token expires I guess, something strange for me starts: chrome devtools network screenshot

App gets token but from account page (http://localhost:8080/auth/realms/my_pim/account) it gets 401 (unauthorized) status. After that it can't get a new token, but then somehow gets it and again gets 401 from the account page. And goes through an infinite loop of redirecting. In keycloak server console I see this.

I don't know what to do with this.

My code:

keycloak.ts

import keycloak, { KeycloakInstance } from 'keycloak-js';


const currentConfigName = process.env.NODE_ENV === 'production' ? 'prod' : 'dev';

const keycloakClient: KeycloakInstance = keycloak(`/keycloak/config.${currentConfigName}.json`);


export default keycloakClient;

config.dev.json

{
   "realm": "my_pim",
   "auth-server-url": "http://localhost:8080/auth/",
   "ssl-required": "external",
   "resource": "pim_test",
   "public-client": true,
   "confidential-port": 0
}

App.tsx

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

import Cookies from 'universal-cookie';


const App = (): any => {
  const dispatch = useDispatch();

  const cookies = new Cookies();

  const eventLogger = (event: unknown, error: unknown) => {
      console.log('onKeycloakEvent', event, error);
  };

  const tokenLogger = (token: any) => {
      if (token.token) {
          console.log('onKeycloakTokens', token);
          cookies.remove('user_token');
          cookies.set('user_token', token.token, { path: '/' });
          dispatch(actions.setAuth(true));
      }
  };

  return (
      <BrowserRouter>            
          <ReactKeycloakProvider
          initOptions={{ onLoad: 'login-required' }}
          onTokens={tokenLogger}
          onEvent={eventLogger}
          authClient={keycloak}>
              <div className="app-wrapper">
                // my components here
              </div>
          </ReactKeycloakProvider>
      </BrowserRouter>
  );
};

export default App;
0 Answers
Related