Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
530 views
Welcome To Ask or Share your Answers For Others

1 Answer

Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...