Reading Time: 5 minutes
Today we are going to see how we can implement Google authentication in our React Native app.
Assuming our React Native project is initialized, we’re going to use the library (https://docs.expo.dev/versions/latest/sdk/auth-session/ ).
First, open app.json and add the fields ““name ” and ““slug ”:
"expo": {
"name": "App_Name",
"slug": "App_Name",
And inside app.json in the iOS section:
"ios": {
"bundleIdentifier": "com.app_name",
You also need to add the package in Android:
"android": {
"package": "com.app_name",
Now, you need to sign in to the Google Developer Console (https://cloud.google.com/developers?hl=en ):
Click on > Get Started for Free and join.
Once inside, click on Console .
Inside the console, you need to create a new project. Click on the drawer that appears in the top left corner of the title where it says Google Cloud (in my case, there is already a project):
A new window will open, and you can choose “New Project”:
Now add the desired name and click on Create .
Once created, select your project.
Now click on the navigation menu:
Choose APIs & Services and then Credentials .
Click on Create Credentials and choose OAuth client ID .
Choose Android or iOS , depending on your needs.
Enter the name of your app and the package name (com.app_name):
Click on Create .
You will receive your Client ID and Client Secret . Save them for later use.
Now let’s install the necessary packages:
expo install expo-google-app-auth expo-constants
Open the file where you want to implement the authentication (for example, App.js ) and import the necessary packages:
import * as Google from 'expo-google-app-auth';
import Constants from 'expo-constants';
Now we will create a function for Google authentication:
const signInWithGoogleAsync = async () => {
try {
const config = {
iosClientId: Constants.manifest.extra.iosClientId,
androidClientId: Constants.manifest.extra.androidClientId,
scopes: ['profile', 'email'],
};
const { type, accessToken, user } = await Google.logInAsync(config);
if (type === 'success') {
// User successfully authenticated
console.log('User authenticated!', user);
// You can now do something with the user data
} else {
// Authentication failed
console.log('Authentication failed!');
}
} catch (error) {
console.log('Error: ', error.message);
}
};
Add a button or any other UI element to trigger the authentication process:
Sign in with Google
That’s it! Now you have implemented Google authentication in your React Native app.
Remember to replace App_Name
with the actual name of your app and com.app_name
with the appropriate package name.
PIPE
Post Views: 8
Related