React Native

View on Github

React Native

Gravatar for martin.walsh@auth0.com
By Martin Walsh

This tutorial demonstrates how to add user login to a React Native application using Auth0. We recommend that you log in to follow this quickstart with examples configured for your account.

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it out on Github.

View on Github
System requirements: React Native 0.62.2 | NodeJS 10.16

New to Auth? Learn How Auth0 works, how it integrates with Native Applications and which protocol it uses.

Configure Auth0

Get Your Application Keys

When you signed up for Auth0, a new application was created for you, or you could have created a new one. You will need some details about that application to communicate with Auth0. You can get these details from the Application Settings section in the Auth0 dashboard.

App Dashboard

When using the Default App with a Native or Single Page Application, ensure to update the Token Endpoint Authentication Method to None and set the Application Type to either SPA or Native.

You need the following information:

  • Domain
  • Client ID

If you download the sample from the top of this page, these details are filled out for you.

Install Dependencies

How to install the React Native Auth0 module.

Please refer to the official documentation for additional details on React Native.

Yarn

yarn add react-native-auth0

For further reference on yarn, check their official documentation.

npm

npm install react-native-auth0 --save

Additional iOS step: install the module Pod

CocoaPods is the package management tool for iOS that the React Native framework uses to install itself into your project. For the iOS native module to work with your iOS app you must first install the library Pod. If you're familiar with older React Native SDK versions, this is similar to what was called linking a native module. The process is now simplified:

Change directory into the ios folder and run pod install.

cd ios
pod install

The first step in adding authentication to your application is to provide a way for your users to log in. The fastest, most secure, and most feature-rich way to do this with Auth0 is to use the hosted login page.

Universal Login

Integrate Auth0 in Your Application

Configure Android

Open your app's build.gradle file (typically at android/app/build.gradle) and add the following manifest placeholders:

android {
    defaultConfig {
        // Add the next line
        manifestPlaceholders = [auth0Domain: "${account.namespace}", auth0Scheme: "${applicationId}"]
    }
    ...
}

The applicationId value will be auto-replaced on runtime with the package name or id of your application (e.g. com.example.app). You can change this value from the build.gradle file. You can also check it at the top of your AndroidManifest.xml file.

Configure iOS

In the file ios/<YOUR PROJECT>/AppDelegate.m add the following:

#import <React/RCTLinkingManager.h>

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

Next you will need to add a URLScheme using your App's bundle identifier.

Inside the ios folder open the Info.plist and locate the value for CFBundleIdentifier

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

then below register a URL type entry using the value of CFBundleIdentifier as the value for the CFBundleURLSchemes

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

If your application was generated using the React Native CLI, the default value of $(PRODUCT_BUNDLE_IDENTIFIER) dynamically matches org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier). For the sample app, this value matches com.auth0samples.

Take note of this value as you'll be using it to define the callback URLs below. If desired, you can change it using XCode in the following way:

  • Open the ios/<YOUR PROJECT>.xcodeproj file or run xed ios on a Terminal from the app root.
  • Open your project's or desired target's Build Settings tab and find the section that contains "Bundle Identifier".
  • Replace the "Bundle Identifier" value with your desired application's bundle identifier name.

For additional information please read react native docs.

Configure Callback URLs

A callback URL is a URL in your application where Auth0 redirects the user after they have authenticated. The callback URL for your app must be added to the Allowed Callback URLs field in your Application Settings. If this field is not set, users will be unable to log in to the application and will get an error.

iOS callback URL

{PRODUCT_BUNDLE_IDENTIFIER}://YOUR_DOMAIN/ios/{PRODUCT_BUNDLE_IDENTIFIER}/callback

Remember to replace {PRODUCT_BUNDLE_IDENTIFIER} with your actual application's bundle identifier name.

Android callback URL

{YOUR_APP_PACKAGE_NAME}://YOUR_DOMAIN/android/{YOUR_APP_PACKAGE_NAME}/callback

Remember to replace {YOUR_APP_PACKAGE_NAME} with your actual application's package name.

Configure Logout URLs

A logout URL is a URL in your application that Auth0 can return to after the user has been logged out of the authorization server. This is specified in the returnTo query parameter. The logout URL for your app must be added to the Allowed Logout URLs field in your Application Settings. If this field is not set, users will be unable to log out from the application and will get an error.

iOS logout URL

{PRODUCT_BUNDLE_IDENTIFIER}://YOUR_DOMAIN/ios/{PRODUCT_BUNDLE_IDENTIFIER}/callback

Remember to replace {PRODUCT_BUNDLE_IDENTIFIER} with your actual application's bundle identifier name.

Android logout URL

{YOUR_APP_PACKAGE_NAME}://YOUR_DOMAIN/android/{YOUR_APP_PACKAGE_NAME}/callback

Remember to replace {YOUR_APP_PACKAGE_NAME} with your actual application's package name.

Add authentication with Auth0

Universal login is the easiest way to set up authentication in your application. We recommend using it for the best experience, best security and the fullest array of features.

You can also embed login functionality directly in your application. If you use this method, some features, such as single sign-on, will not be accessible. To learn how to embed functionality using a custom login form in your application, follow the Custom Login Form Sample. Make sure you read the Browser-Based vs. Native Login Flows on Mobile Devices article to learn how to choose between the two types of login flows.

First, import the Auth0 module and create a new Auth0 instance.

import Auth0 from 'react-native-auth0';
const auth0 = new Auth0({ domain: 'YOUR_DOMAIN', clientId: 'YOUR_CLIENT_ID' });

Then present the hosted login screen, like this:

auth0
    .webAuth
    .authorize({scope: 'openid profile email'})
    .then(credentials =>
      // Successfully authenticated
      // Store the accessToken
      this.setState({ accessToken: credentials.accessToken })
    )
    .catch(error => console.log(error));

Upon successful authentication the user's credentials will be returned, containing an access_token, an id_token and an expires_in value.

For more information on the accessToken, refer to Access Token.

Log the user out

To log the user out, redirect them to the Auth0 log out endpoint by calling clearSession. This will remove their session from the authorization server. After this happens, remove the Access Token from the state.

 auth0.webAuth
    .clearSession({})
    .then(success => {
        Alert.alert(
            'Logged out!'
        );
        this.setState({ accessToken: null });
    })
    .catch(error => {
        console.log('Log out cancelled');
    });
Use Auth0 for FREE