I am using React Router v5, keycloak-js and @react-keycloak/web to implement route guarding and user authentication. The main idea is that the SecuredPage component is to be protected from unauthenticated users, wherein they should be redirected to /login if they are not yet logged in.
Here is how my app is set up:
App.js:
const App = (props) => {
const keycloak = new Keycloak("/keycloak.json");
return (
<div className="app">
<ReactKeycloakProvider authClient={keycloak}>
<Switch>
<Route path="/login" exact>
<Login />
</Route>
<RouteGuard path="/secured" exact component={SecuredPage} />
</Switch>
</ReactKeycloakProvider>
</div>
);
};
And the following is my RouteGuard component:
const RouteGuard = ({ component: Component, ...rest }) => {
const { keycloak } = useKeycloak();
const isLoggedIn = keycloak.authenticated;
return (
<Route
{...rest}
render={(props) => {
if (isLoggedIn) {
console.log("USER IS LOGGED IN, RENDERING COMPONENT");
return <Component />;
} else {
console.log("USER NOT LOGGED IN, REDIRECT TO LOGIN");
return (
<Redirect
to={{
pathname: "/login",
state: {
error: "You must login to continue.",
from: props.location.pathname,
redirected: true,
},
}}
/>
);
}
}}
/>
);
};
The app works great if I manually navigate to /secured, then I get redirected to keycloak's login page. The problem is, once I am already logged in and I go to /secured page, and from within that page, reload (F5), I get thrown into /login even though my keycloak session is still up. This doesn't happen if I navigate normally or when using the back and forward buttons of the browser. It only seems to happen on page reload or when I manually type into the URL bar.
I'm thinking maybe the RouteGuard component returns the Redirect before the isLoggedIn variable gets initialized during a page reload, but I can't figure out how I should make it so that the RouteGuard component's redirect waits to check the isLoggedIn variable?
Is there a better way on implementing Route Guards using React Router?