Photo by Cookie the Pom on Unsplash

Use react-native-inappbrowser-reborn with federated cognito auth

I just come across a question on StackOverflow about how to make a social sign-in more user-friendly in ReactNative when using Federated Cognito authentication. Because if you use the default setup, it will first ask user confirmation and then open the browser for sign in and then open up the app again. This is not a very good UX. So let's see how we can do that in a more intuitive way.

First, we will be going to use an awesome module react-native-inappbrowser-reborn. So please install it with this command

npm i react-native-inappbrowser-reborn
OR
yarn add react-native-inappbrowser-reborn
You might have to install pods or setup gradle based on your platform. You can read more about the setup here https://www.npmjs.com/package/react-native-inappbrowser-reborn

Let’s configure it for our use-case. Please create a new file, url-opener.js, as in the given example below

Now we need to change our Amplify configuration to use our new module. So please update the amplify config to use it as following

import urlOpener from './url-opener';
Amplify.configure({
Auth{
...,
oauth{
...,
urlOpener
}
}
});

Good, now whenever we call Auth.federatedSignIn it will open up the browser inside the app. Cool!

But, once you logged in with any federated entity, the browser might not close automatically. Here is a workaround to close the browser immediately after a successful login. It may be different than your setup but you will get the idea.

You need to add the following code to your login component.

First import Hub from amplify/core and react-native-inappbrowser-reborn.

import InAppBrowser from ‘react-native-inappbrowser-reborn’;
import { Hub } from '@aws-amplify/core';

Then attach a new auth listener to Hub

React.useEffect(() => {
Hub.listen("auth", handleAuth)
return () => Hub.remove('auth', handleAuth)
}, []);

Finally, define the function

Hope it helps! Thank You

--

--