I would like to authenticate my react app - PWA based on create-react-app with keycloak server, and once user is authenticated then i would like them to be able to browser side offline with valid token that i have cached in localStorage but even when passed tokens to keycloak init, i can see user redirected to keycloak auth server.
library version:-
"keycloak-js": "^12.0.2",
"@react-keycloak/web": "^3.4.0",
App.tsx
class App extends React.Component {
tokens: any;
constructor(props: any) {
super(props);
this.tokens = JSON.parse(localStorage.getItem(kcTokens) || '{}');
}
onTokens = (tokens: Pick<AuthClient, "idToken" | "refreshToken" | "token">) => {
localStorage.setItem(kcTokens, JSON.stringify(tokens));
}
onEvent = (event: AuthClientEvent, error?: AuthClientError | undefined) => {
console.log('onKeycloakEvent', event, error);
}
render() {
return (
<ReactKeycloakProvider
authClient={keycloak}
initOptions={{
onLoad: 'check-sso',
...this.tokens
}}
LoadingComponent={loadingComponent}
onEvent={this.onEvent}
onTokens={this.onTokens}
>
<AppRouter />
</ReactKeycloakProvider>
)
}
}
AppRouter.tsx
const AppRouter = () => {
return (
<Router history={history}>
<Switch>
<PrivateRoute path="/" exact component={Home}></PrivateRoute>
</Switch>
</Router>
)
}
PrivateRoute.tsx
const PrivateRoute : React.FC<PrivateRouteProps> = ({ component: Component, ...rest }) => {
const { keycloak } = useKeycloak();
React.useEffect(() => {
if (!keycloak?.authenticated) {
keycloak.login();
}
}, [keycloak]);
return (
<Route
{...rest}
render={props => (
keycloak?.authenticated && <Component {...props} />
)}
/>
);
}
question from:https://stackoverflow.com/questions/65934005/keycloak-js-client-in-pwa-not-using-cached-token-from-storage