2

I am trying to use React with Keycloak, after initializing the realm, users, and client. Every time I npm start my react project it keeps refreshing every second and changing the state

For ex:

http://localhost:3000/#state=f9fe446d-358e-4206-811f-fe05f37a8981&session_state=5b741a8e-28d2-4850-a285-2e139fe5c204&code=fe3ca9e6-37f1-41e8-91be-c2502e86b071.5b741a8e-28d2-4850-a285-2e139fe5c204.10d54989-1e8a-486b-b33b-4a164f9f84ab

after one second later:

http://localhost:3000/#state=37e5d6e5-18e0-4578-89cc-01ca41f397c9&session_state=5b741a8e-28d2-4850-a285-2e139fe5c204&code=c1488eb9-42ed-40d2-aee9-eff76e3ceabe.5b741a8e-28d2-4850-a285-2e139fe5c204.10d54989-1e8a-486b-b33b-4a164f9f84ab

App.js

 <div>
  <ReactKeycloakProvider authClient={keycloak}>
    <Nav />
    <BrowserRouter>
      <Routes>
        <Route exact path="/" element={<WelcomePage />} />
        <Route path="/secured" element={<SecuredPage />} />
      </Routes>
    </BrowserRouter>
  </ReactKeycloakProvider>
</div>

Secured Page:

<div>
  <ReactKeycloakProvider authClient={keycloak}>
    <Nav />
    <BrowserRouter>
      <Routes>
        <Route exact path="/" element={<WelcomePage />} />
        <Route
          path="/secured"
          element={
            <PrivateRoute>
              <SecuredPage />
            </PrivateRoute>
          }
        />
      </Routes>
    </BrowserRouter>
  </ReactKeycloakProvider>
</div>

Private Route

import { useKeycloak } from "@react-keycloak/web";

const PrivateRoute = ({ children }) => {
  const { keycloak } = useKeycloak();

  console.log(keycloak);

  const isLoggedIn = keycloak.authenticated;

  return isLoggedIn ? children : null;
};

export default PrivateRoute;

Keycloak file:

const keycloak = new Keycloak({
  url: "http://localhost:8080/auth",
  realm: "keycloak-react-auth",
  clientId: "react-auth",
});

Realm's configuration in Keycloak

User's configuration in Keycloak

Client's configuration in Keycloak

Illyrian
  • 429
  • 4
  • 16

1 Answers1

1

I have a similar problem with vue.js. For me I found out it is caused by the iframe that is created to watch the current session status and third-party-cookies missing a sameSite attribute. The iframe can be disabled by passing checkLoginIframe: false as an option to the init function. It's a workaround to stop the page from reloading. Not really a fix, because you lose the functionality to get the status.

This was already answered here: Keycloak: Session cookies are missing within the token request with the new Chrome SameSite/Secure cookie enforcement

However since I found your question first, I decided to answer anyway.

Here's a link to the keycloak documentation about the status iframe and the issue in modern browsers: https://www.keycloak.org/docs/latest/securing_apps/index.html#session-status-iframe https://www.keycloak.org/docs/latest/securing_apps/index.html#_modern_browsers

micha
  • 321
  • 3
  • 16