react-keycloak / react-native-keycloak

React Native components for Keycloak
MIT License
170 stars 45 forks source link

Unable to access keycloak session in any other functional component & preserve session #100

Open satishaxtria opened 2 years ago

satishaxtria commented 2 years ago

Describe the bug

Adding KeycloakProvider

let kcConfig = new RNKeycloak({
            url: '<our host url>',
            realm: '<realm name>',
            clientId: <client-id>
});

<ReactNativeKeycloakProvider
                authClient={kcConfig}
                initOptions={{
                    redirectUri: (new AppConfig()).getKeyCloakRedirectUri()
                }}>

                <Provider store={store}>
                    <PersistGate loading={null} persistor={persistor}>
                        {App.renderStack(loginState)}
                        <PushNotificationHandler/>
                    </PersistGate>
                    <FlashMessage position={'top'} />
                </Provider>
</ReactNativeKeycloakProvider>

Login with keycloak

const KCLogin = () => {
    const { keycloak } = useKeycloak();
    return (
        <View style={[ContainerStyles.container, styles.container]}>
            <ActionButton
                title={'Login'}
                onPress={() => {
                    keycloak?.login().then(() => {
                            console.log('Login Success for FI.');
                }}
            />
        </View>
    )
}

Accessing Keycloak Session --> Gives undefined token, idToken, refreshToken and authenticated = false

const HomeScreen = () => {
    const { keycloak, initialized } = useKeycloak();
    console.log('Keycloak Session', keycloak);
    return (
        <View>
            <Label text={'Home Screen'} />
        </View>
    )
}

To Reproduce

  1. Add Keycloak provider.
  2. Create a functional component to login using keycloak and login
  3. Now access login session data from Keycloak in any other functional component. session value are undefined in any other functional component.

Expected behavior Keycloak session should be accessible in any other functional component. Also it should be re initialised when App re launched. or there should be some persistent mechanism to store the session and retrieve when app re launched.

Screenshots NA

Smartphone

Additional context NA

kosbog commented 1 year ago

Almost the same. I get authenticated = false every time, even on refresh success.

standreinmcp commented 1 year ago

I also encountered it last few days. Not sure what is the issue, we're also using a persisting mechanism inside the app ( redux-persist ) and every time we close and open the app, it refreshes the session by opening and closing the inAppBrowser. Basically it should refresh only when the tokens expire, not every time the app opens.

sravanvudem commented 6 months ago

@standreinmcp try this once

configure this in your App.js file

<ReactNativeKeycloakProvider autoRefreshToken authClient={keycloak} onTokens={tokens => { if (tokens?.token != 'undefined') { AsyncStorage.setItem('Tokens', JSON.stringify(tokens)) } }} initOptions={{ redirectUri: 'ur url', postLogoutRedirectUri: 'your url', inAppBrowserOptions: {}, }}>

           useEffect(() => {
fetchData();
setTimeout(() => {
  // navigation.navigate('HomeTabs');
  navigation.navigate(keycloak?.authenticated ? 'HomeTabs' : 'AuthStack');
}, 100);

}, []);

configure this in your landing Screen

i.e the screen which render as first Screen on DOM

const fetchData = async () => { let tokens = await AsyncStorage.getItem('Tokens'); let finalTokens = JSON.parse(tokens); // console.log('finalTokens', finalTokens); keycloak.init({ refreshToken: finalTokens?.refreshToken, token: finalTokens?.token, idToken: finalTokens?.idToken, redirectUri: 'your url', }); keycloak.onTokenExpired = () => { keycloak .updateToken(5) .then(() => { // console.log('onTokenExpired', 'token updated'); }) .catch(err => { console.log(err); }); }; };