How to integrate Auth0 to React native
Tags: javascript, reactnativedevelop, react, reactnative
Published: 2019-08-19 06:05:58

---
title: How to integrate Auth0 to React native
published: true
tags: javascript,react-native-develop,reactjs,react-native
canonical_url: https://kriss.io/how-to-integrate-auth0-to-react-native/
cover_image: https://cdn-images-1.medium.com/max/1024/1*uW9Dm-0fOahwdm0yPfgwOQ.png
---


In this tutorial, we are going to learn how to implement **Auth0** to our [React Native chat app](https://instamobile.io/app-templates/react-native-chat-app-template/). [Auth0](https://auth0.com) 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](https://github.com/krissnawat/pubnub-react-native-chat/tree/add_auth0).
3. We are going to add Auth0 to our [existing app](https://github.com/krissnawat/pubnub-react-native-chat/tree/add_auth0).

### Requirements

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

- Node.js v8.x.x or higher installed along with npm/yarn.
- Android or iOS simulator or hardware device.
- [Already setup React native development environment](https://developers.facebook.com/docs/react-native/getting-started).
- A starter boiler plate project available [here](https://github.com/krissnawat/pubnub-react-native-chat/).

Now, let us begin with the process.

### Setup Starter Project

In this step, we are going to work with this [GitHub repo](https://github.com/krissnawat/pubnub-react-native-chat/). We need to go through the following git command to clone the [starter boilerplate](https://facebook.github.io/react-native/docs/getting-started.html#content) 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](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:

![](https://cdn-images-1.medium.com/max/681/1*5hlHzdEO2jknNYSe_mxZMw.png)

### Creating a New Auth0 App

In this step, we are going to create an Auth0 application. We need to navigate to the [Auth0 dashboard](http://auth0.com) and then either create an Auth0 account or sign in to an existing Auth0 account. We will then follow the following steps:

![](https://cdn-images-1.medium.com/max/959/1*g9U32QleKeaDaWyhVcY4yw.png)

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:

![](https://cdn-images-1.medium.com/max/841/1*gZNPpd3vlQlxozTKvHronA.png)

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

![](https://cdn-images-1.medium.com/max/896/1*8WkIjdwawAfS-q7t0Pgg8Q.png)

### 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_](https://facebook.github.io/react-native/docs/linking.html)_._

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](https://developer.android.com/studio/build/gradle-tips.html#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_](https://tools.ietf.org/html/rfc3986#page-17)_. A “Redirect URI is not valid” error will raise if this format is not respected._

So, we need to go to the [Auth0 Dashboard](https://manage.auth0.com/#/applications), 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**](https://github.com/auth0/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:

![](https://cdn-images-1.medium.com/max/751/1*ZZbSxWD31_1yEGfZTRvZ2g.png)

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.

![](https://cdn-images-1.medium.com/max/398/1*wI-7mbhqopII9rRKmLnZCQ.gif)

![](https://cdn-images-1.medium.com/max/364/0*EfC-cTSPc0fXcZVG.gif)

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](https://github.com/krissnawat/pubnub-react-native-chat/tree/add_auth0).

### Disclosure
This post includes affiliate links; I may receive compensation if you purchase products or services from the different links provided in this article.

* * *