react-native-keycloak
react-native-keycloak copied to clipboard
Unable to access keycloak session in any other functional component & preserve session
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
- Add Keycloak provider.
- Create a functional component to login using keycloak and login
- 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
- Device: iPad
- OS: iOS 15.1
- Version 15.1
Additional context NA
Almost the same. I get authenticated = false every time, even on refresh success.
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.
@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); }); }; };