fbpx

How to integrate Auth0 to React native

How to integrate Auth0 to React native

Launch the next Yelp in minutes

Download this gorgeous React Native Store Locator app template to create your own store finder app in just a few minutes. By using this fully-coded starter kit written in React Native, you’re saving weeks of design and development and can focus on other important efforts such as customer engagement and marketing.

Check out here

In this tutorial, we are going to learn how to implement Auth0 to our React Native chat app. Auth0 is a security platform that provides authentication and authorization as a service. It gives developers an option to make their application more secure without having to be a security expert. So, in this tutorial, we are going to incorporate it into our React Native app to make it more secure.

Before we go into details, let me summarize the process to get the gist of the overall tutorial:

  1. We are going to create an Auth0 account and app.
  2. We are going to install the Auth0 React native package (react-native-auth) to the existing app.
  3. We are going to add Auth0 to our existing app.

Requirements

Here’s a complete list of plugins, packages, platforms, and services we’re going to need to gain something from this tutorial:

Now, let us begin with the process.

Setup Starter Project

In this step, we are going to work with this GitHub repo. We need to go through the following git command to clone the starter boilerplate project into your local directory:

First, we need to clone the GitHub repo using the following command in our Git console:

git clone

https://github.com/krissnawat/pubnub-react-native-chat

Next, we will navigate to the project by running the following command:

cd pubnub-react-native-chat

Then, we need to checkout to the before_use_auth0 branch with the following command:

git checkout before_use_auth0

Now, we have our starter React Native boilerplate project as shown in the GitHub clone completion screenshot below:

Creating a New Auth0 App

In this step, we are going to create an Auth0 application. We need to navigate to the Auth0 dashboard and then either create an Auth0 account or sign in to an existing Auth0 account. We will then follow the following steps:

We need to choose the “Native” application type since our application is mobile-based. We need to give a name to our Auth0 app, i.e., “ChatApp.” Finally, after entering the name and selecting the application type for the app, we need to click on the “CREATE” button as we can see in the screenshot below:

As a result, we have our new Auth0 app. After clicking on the “Settings” tab, we can now see the app’s console:

Configurations

Here, we are going to configure the Auth0 app for Android and iOS to integrate it into our React Native app.

For Android

In the file android/app/src/main/AndroidManifest.xml, we need to make sure that the MainActivity of the app has a launchMode value of singleTask and that it has the following intent filter as shown in the code snippet below:

<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data
        android:host="YOUR_AUTH0_DOMAIN"
        android:pathPrefix="/android/${applicationId}/callback"
        android:scheme="${applicationId}" />
</intent-filter>

So, if we have samples.auth0.com as our Auth0 domain, we would have the following MainActivity configuration:

<activity
   android:name=".MainActivity"
   android:label="@string/app_name"

android:launchMode=”singleTask”

  android:configChanges="keyboard|keyboardHidden|orientation|screenSiz  e"
   android:windowSoftInputMode="adjustResize">
<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />

<data android:host=”samples.auth0.com” android:pathPrefix=”/android/${applicationId}/callback” android:scheme=”${applicationId}” />

</intent-filter>
</activity>

For more info please read the React native docs.

To reduce the potential for conflict, which may be caused by the presence of different versions of the Android support libraries, you may wish to configure project-wide properties. Setting the Compile and Target SDK versions, Build Tools version, and Support Library version in your root project’s build.gradle file will make react-native-auth0 and many other React Native modules use them.

For iOS

Inside the ios folder, we need to locate the file ios/pubnubchat/AppDelegate.m and add the following piece of code to it:

#import <React/RCTLinkingManager.h>
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
  return [RCTLinkingManager application:application openURL:url
                      sourceApplication:sourceApplication annotation:annotation];
}

Then, inside our ios folder, we need to open the ios/pubnubchat/Info.plist file and find the value for CFBundleIdentifier, the example is shown in the code snippet below:

<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>

And then we need to register or change the URL type entry using the value of CFBundleIdentifier as the value of CFBundleURLSchemesasin the pubnubchat/ios/Info.plist file, as shown in the code snippet below:

<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>

Callback URL(s)

Callback URLs are the URLs that Auth0 invokes after the authentication process is successful. Auth0 routes our application back to this URL and appends additional parameters to it, including a token. Since callback URLs can be manipulated, we will need to add this URL to our Application’s Allowed Callback URLs for security. This will enable Auth0 to recognize these URLs as valid. If omitted, authentication will not be successful.

Callback URLs must have a valid scheme value as defined by the specification. A “Redirect URI is not valid” error will raise if this format is not respected.

So, we need to go to the Auth0 Dashboard, select our application, and make sure that Allowed Callback URLs contains the following:

For iOS,

{YOUR_BUNDLE_IDENTIFIER}://${YOUR_AUTH0_DOMAIN}/ios/{YOUR_BUNDLE_IDENTIFIER}/callback

For Android,

{YOUR_APP_PACKAGE_NAME}://{YOUR_AUTH0_DOMAIN}/android/{YOUR_APP_PACKAGE_NAME}/callback

For example, we can take the values from the following code snippet and save the changes:

// iOS
org.reactjs.native.example.pubnubchat://kris101.auth0.com/ios/org.reactjs.native.example.pubnubchat/callback
// Android
com.pubnubchat://kris101.auth0.com/android/com.pubnubchat/callback

Adding Auth0 to Our App

In this step, we are going to install and configure Auth0 into our React Native app. For this, we are going to use the react-native-auth0 package. This package is a toolkit for Auth0 APIs. To install this package, we can use either npm or yarn, as shown below:

In projects directory,

Using npm,

npm install react-native-auth0 --save

Or using yarn,

yarn add react-native-auth0

After we have added package and configuration, we need to run the following installation command:

react-native link react-native-auth0

Next, we are linkingreact-native-auth0native module successfully as we can see in the screenshot below:

After we have added the package and configuration, we need to run the following installation command:

yarnor npm install

Now, we need to open our src/components/Login.js component and import Auth0 module from react-native-auth0 package. Then, we need to define a new instance with domain and clientID, as shown in the code snippet below:

import React, { Component } from "react";
import Auth0 from "react-native-auth0";
const auth0 = new Auth0({
  domain: "xxxxxx.auth0.com",
  clientId: "xxxxxxxxxxxxxxxxxx"
});

Now, we need to create a new function named Auth0Login() to handle authentication flow by using the code provided in the code snippet below in src/components/Login.js file:

Auth0Login = () => {
    auth0.webAuth
      .authorize({
        scope: "openid email"
      })
      .then(res => {
        console.log(res);
        auth0.auth
          .userInfo({ token: res.accessToken })
          .then(user => {
            this.props.navigation.navigate("MainChat", {
              username: user.email
            });
          })
          .catch(console.error);
      })
      .catch(error => console.log(error));
 };

First, we start with web authentication. After we get a successful callback, we will get user info with an access token. Then, we need to redirect the user to the next screen, i.e., MainChat with user data (i.e., username with the user’s email).

Lastly, we need to create a button in the view to trigger the Auth0Login() function as shown in the code snippet in src/components/Login.js file:

<View style={styles.btnContiner}>
    <TouchableOpacity style={styles.btn} onPress={() => this.login()}>
       <Text style={styles.btntext}>Login</Text>
    </TouchableOpacity>
    <TouchableOpacity style={styles.btn} onPress={() => this.Auth0Login()} >
       <Text style={styles.btntext}>Login with Auth0</Text>
    </TouchableOpacity>
</View>

Now, when everything is done, we can start iOS simulator with the following command:

react-native run-ios or react-native run-android

Let us test for overall configuration and code to see if it works properly. In the simulation below, we see that when the “Login with Auth0” button is clicked, we are redirected to the login page. Once there, we see that we can click on the “LOG IN WITH GOOGLE” button. That will then redirect us to the MainChat screen.

As we can see in the simulation above, the Auth0 authentication works properly. This means that we have successfully integrated Auth0 into our React Native app.

Conclusion

In this tutorial, we learned how to create an Auth0 app and configure it into our React Native app. We learned how to configure Auth0 for both Android and iOS platforms. Then, we got to experience a detailed process on how to handle the authentication flow to finish our React Native app. The overall code for this tutorial can be found in this GitHub repo.

taqman

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.