A Comprehensive Guide to Auth0 Integration in React Native

When developing any product or app, it is essential to include login and signup features. These can be achieved using various methods such as email-password, social logins, or OTP. So if we want to implement all these login features in react native we must import the required SDKs and dependencies related to it.

However, to avoid this situation we can use other approaches. So Auth0 emerges as a superior solution for providing secure authentication and authorization services for your app. Below are some of the many features offered by Auth0.

➡️ Email-password login.
➡️ Social app login like Google, Facebook, Apple, Microsoft, etc.
➡️ Multi-factor authentication.
➡️ Forgot password and change password.
➡️ Biometric authentication.
➡️ UI customization.

Related read: What is Auth0? Features, Benefits And Its Implementation

Configure Auth0

If you do not possess an Auth0 account, you can sign up for one here on the official site of Auth0.

Now after setting up an account you have to go to the dashboard and need to check if any application is available or not. You can create a separate application for your app also. Here I have created a native-type app.

create application
Fig. Creating New App In Auth0 Dashboard

You will need Domain and Client ID when we implement login functionality.

react native autho demo

Install Dependencies & Pods

yarn add react-native-auth0

cd ios && pod install

iOS Configurations

Go to ios/<project_name>/AppDelegate.m and add the following.

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
return [RCTLinkingManager application:app openURL:url options:options];
}

Go to ios/<project_name> and open info.plist and add the following if not available.

<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>None</string>
<key>CFBundleURLName</key>
<string>auth0</string>
<key>CFBundleURLSchemes</key>
<array>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
</array>
</dict>
</array>

You can Check Out Our Video on Introduction to Auth0 Below:

Android Configurations

To implement the necessary configurations, navigate to the android/app/build.gradle file and add the manifestPlaceholders block, which requires two parameters: the Auth0 domain and the android applicationId.

The code snippet below demonstrates how to do this:

android {
defaultConfig {
manifestPlaceholders = [auth0Domain: "your domain", auth0Scheme: "yourapplicationId"]
}
}

Configure Callback URLs in Auth0 Dashboard

The callback URL is a crucial component in our application, as it allows Auth0 to redirect the user after a successful login, providing additional parameters that we can utilize for user verification and authentication.

To ensure its proper functioning, we need to add the callback URL in the Auth0 dashboard under “Your Application’s Settings” (Dashboard -> Applications -> Select Your Application -> Settings -> Application URIs).

Failing to add these URLs may result in an error message while implementing the login with the Auth0 feature. Hence, it is essential to include the correct callback URL in the Auth0 dashboard settings to enable smooth and secure user authentication and verification processes.

For iOS:

{PRODUCT_BUNDLE_IDENTIFIER}://{yourDomain}/ios/{PRODUCT_BUNDLE_IDENTIFIER}/callback

For Android:

{YOUR_APP_PACKAGE_NAME}://{yourDomain}/android/{YOUR_APP_PACKAGE_NAME}/callback

For example:

iOS : com.starwarsappdemo://dev-qa-stag.us.auth0.com/ios/com.starwarsappdemo/callback

Android : 
com.starwarsappdemo://dev-qa-stag.us.auth0.com/android/com.starwarsappdemo/callback

Configure LogOut URLs in Auth0 Dashboard

The logout URL is an important component in our application that Auth0 utilizes to redirect the user after they have successfully logged out from the authentication server. To ensure the proper functioning of the logout feature, it is necessary to add the appropriate logout URL in the Auth0 dashboard. If the logout URL is not properly configured, there is a possibility of encountering an error message when implementing the logout feature.

For iOS:

{PRODUCT_BUNDLE_IDENTIFIER}://{yourDomain}/ios/{PRODUCT_BUNDLE_IDENTIFIER}/callback

For Android:

{YOUR_APP_PACKAGE_NAME}://{yourDomain}/android/{YOUR_APP_PACKAGE_NAME}/callback

For example:

iOS : 
com.starwarsappdemo://dev-qa-stag.us.auth0.com/ios/com.starwarsappdemo/callback
Android : 
com.starwarsappdemo://dev-qa-stag.us.auth0.com/android/com.starwarsappdemo/callback

App-CallBack-Urls

Implement Login in React Native App

To implement Auth0 authentication in our application, we need to import the Auth0Provider component from the Auth0 package. This component will be used to wrap up our entire application, enabling authentication functionalities throughout. The Auth0Provider component requires two parameter values: domain and clientId.

Below is an example of how you can add the necessary code:

import {Auth0Provider} from 'react-native-auth0';

const App = () => {
try {
return (
<Auth0Provider
domain={“your app domain”}
clientId={“your app client id”}>
{/* Your Application code and Business Logic */}
</Auth0Provider>
);
} 
catch (error) {
crashlytics().log('Error in App.');
crashlytics().recordError(error);
}
};

export default App;

To launch the Auth0 login UI, we can utilize the useAuth0 hook from the Auth0 package, which provides convenient access to various props and methods. One of these methods is authorized, which allows us to trigger the login process and display the Auth0 login UI.

Below is an example of how to implement this:

import {useAuth0} from 'react-native-auth0';

const {authorize, user, getCredentials, clearSession, clearCredentials} = useAuth0();

const onPressLoginWithAuth0 = async () => {
try {
await authorize();
} catch (e) {
console.log(error)
}
};

return ( 
<ButtonComponent
title={“Login”}
onPress={onPressLoginWithAuth0}
/>
)

So it will open the UI as given below. You can signup and login also with Auth0 credentials.

Login dashboard auth0After login, you will get user information in the user prop of the useAuth0 hook. Information can be like this.

{
"nickname": "johndoe",
"name": "johndoe@yopmail.com",
"picture": "https://s.gravatar.com/avatar/58aa4a5e3aad68d2d518857fee3ba691?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fjo.png",
"updated_at": "2023-07-27T10:41:13.453Z",
"email": "johndoe@yopmail.com",
"email_verified": false,
"sub": "auth0|64c248a6adf0a94c33d0ad54"
}

The Auth0 package provides an additional asynchronous method called getCredentials, which allows us to obtain further information related to the user’s authentication. By utilizing this method, we can retrieve various user-related data and authentication details.

Below are some examples of the information that can be obtained:

{
"idToken": "eyJhbGciOiJSUzI1Ni........",
"tokenType": "Bearer",
"scope": "openid profile email read:current_user offline_access",
"accessToken": "eyJhbGciOiJSUzI1NiIsInR5cCI6Ik.....",
"refreshToken": "f9hwLH_55Eto0iU396RSopW....",
"expiresIn": 1690543063
}

Log Out the User from the App

To Logout the user from the app we will use the clearCredentials and clearSession methods from the useAuth0 hook. So clearSession will remove the session from the authentication server and clearCredentials will remove the user credentials from the application.

const {authorize, user, getCredentials, clearSession, clearCredentials} = useAuth0();

const onPressLogOutWithAuth0 = () => {
clearCredentials();
clearSession();
};


<ButtonComponent
title={'Log Out'}
onPress={onPressLogOutWithAuth0}
/>

The full code snippet is given below:

import {SafeAreaView, StyleSheet, Text, View} from 'react-native';
import React, {useEffect} from 'react';
import Colors from '../theme/Colors';
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
import {isAndroid} from '../utils/Metrics';
import {ButtonComponent} from '../components';
import {useAuth0} from 'react-native-auth0';
import {Auth0Config} from '../networkConfig/Endpoints';

const Login = () => {
const {authorize, user, getCredentials, clearSession, clearCredentials} =
useAuth0();

useEffect(async () => {
console.log('user-->', user);
if (user) {
console.log('user-->', await getCredentials());
}
}, [user]);

const onPressLoginWithAuth0 = async () => {
try {
await authorize({
scope: Auth0Config.scope,
audience: Auth0Config.audience,
prompt: 'login',
});
} catch (e) {}
};

const onPressLogOutWithAuth0 = () => {
clearCredentials();
clearSession();
};

return (
<View style={styles.container}>
<SafeAreaView />
<KeyboardAwareScrollView
contentContainerStyle={styles.keyboardContainer}
showsVerticalScrollIndicator={false}
bounces={false}
keyboardShouldPersistTaps="handled">
<Text style={styles.loginTitle}>
{user ? 'Welcome to the demo' : 'Login to your account'}
</Text>
{user ? (
<View>
<Text style={styles.loginDescription}>Email : {user?.email}</Text>
<ButtonComponent
title={'Log Out'}
onPress={onPressLogOutWithAuth0}
/>
</View>
) : (
<ButtonComponent title={'Login'} onPress={onPressLoginWithAuth0} />
)}
</KeyboardAwareScrollView>
<SafeAreaView />
</View>
);
};

export default Login;

You can find a recording of the demo here.

coma

Conclusion

In this article, I have provided a comprehensive explanation of Auth0, its features, and the process of integrating Auth0 into a React Native application. We covered the configuration steps required for both iOS and Android platforms, ensuring a smooth setup process.

The integration process involves installing the necessary dependencies and pods, making iOS and Android configurations, and configuring callback URLs and logout URLs in the Auth0 dashboard.

Furthermore, I explained how developers can implement the login and logout functionalities within their React Native applications using the useAuth0 hook. By using this approach, developers can leverage Auth0’s authentication services to enhance the security and productivity of their apps.

Ronak K

React-Native Developer

Ronak is a React-Native developer with more than 4 years of experience in developing mobile applications for Android and iOS. He is dedicated to his work and passion. He worked in different kinds of application industries that have responsive designs. He also has knowledge of how to make an app with expo cli and react-native web and some basic understanding of react.js.

Keep Reading

Keep Reading

Launch Faster with Low Cost: Master GTM with Pre-built Solutions in Our Webinar!

Register Today!
  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?