This guide provides instructions on integrating Authgear with a React Native app. Supported platforms include:
React Native 0.60.0 or higher
Follow this guide to add Authgear to your React Native app in 🕐 10 minutes.
You can find the full code for the demo app for this tutorial in the Github repo here.
Video Guide for React Native
Setup Application in Authgear
Signup for an Authgear Portal account in https://portal.authgear.com/. Or you can use your self-deployed Authgear.
From the Project listing, create a new Project or select an existing Project. After that, we will need to create an application in the project.
Step 1: Create an application in Authgear Portal
Go to Applications on the left menu bar.
You'll see the "New Application" page, or Click ⊕Add Application in the top tool bar.
Input the name of your application and select Native App as the application type. Click "Save".
On the next screen, you will see a list of guides that can help you with setting up, click "Next" to continue.
Step 2: Configure the application
In your IDE, define a custom URI scheme that will be used to redirect users back to your app after they have authenticated with Authgear. For example, in our example app, we will define the following URI scheme:
Now head back to Authgear Portal, and add the URI that you have defined (com.authgear.example.rn://host/path for this example) as an Authorized Redirect URI.
Click "Save" and note the Client ID and Endpoint for your Authgear client application. You can also obtain it again from the Applications list later.
Add User Authentication to React Native App using Authgear SDK
In this section, we'll walk through the steps to create a new React Native app and use the Authgear SDK to add user authentication to the app.
Step 1: Create a React Native app
Run the following command to create a new React Native project:
npx @react-native-community/cli init myapp
cd myapp
For a more detailed guide on how to create a project and set up a development environment for React Native, follow the official documentation of React Native.
Step 2: Install the SDK
Run the following commands from the root directory of your React Native project to install the Authgear SDK:
npm install --exact @authgear/react-native
(cd ios && pod install)
Step 3: Initialize Authgear
In this step, we'll implement the code to initialize an instance of the Authgear SDK which we will be using to interact with the Authgear client application we created earlier.
First, open the App.tsx file in your project then add the following import statements at the top:
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import authgear, { Page, ReactNativeContainer, SessionState, SessionStateChangeReason } from "@authgear/react-native";
Add the following code at the top inside the App() function in App.tsx to configure a new Authgear instance and set up a delegate that will help our app to know the current state of a user's session (whether they're logged in or not):
In this step, you will implement an authenticate() method that calls the authenticate() method of the Authgear SDK. The Login button we added in the previous step calls this authenticate() method to start an authentication flow.
Add the following code to the App() function just after the useEffect() for the configure() method in step 3:
Now save your work and try running your app on Android or iOS using any of the following commands:
Android
npm run android
iOS
npm run ios
When your app opens, if you click on the Login button, you should be redirected to the Authentication UI. However, you can't complete authentication because we are yet to handle the redirect URI.
Step 6: Setup Redirect URI
To finish the integration, set up the app to handle the redirect URI specified in your Authgear client application. This part requires platform-specific integration.
Android
Add the following activity entry to the android/app/src/main/AndroidManifest.xml of your React Native project. The intent system would dispatch the redirect URI to OAuthRedirectActivity and the sdk would handle the rest.
<!-- Your application configuration. Omitted here for brevity -->
<application>
<!-- Other activities or entries -->
<!-- Add the following activity -->
<!-- android:exported="true" is required -->
<!-- See https://developer.android.com/about/versions/12/behavior-changes-12#exported -->
<activity android:name="com.authgear.reactnative.OAuthRedirectActivity"
android:exported="true"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- Configure data to be the exact redirect URI your app uses. -->
<!-- Here, we are using com.authgear.example://host/path as configured in authgear.yaml. -->
<!-- NOTE: The redirectURI supplied in AuthenticateOptions *has* to match as well -->
<data android:scheme="com.authgear.example.rn"
android:host="host"
android:pathPrefix="/path"/>
</intent-filter>
</activity>
</application>
You also need to add a queries section to AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Other elements such <application> -->
<queries>
<intent>
<action android:name="android.support.customtabs.action.CustomTabsService" />
</intent>
</queries>
</manifest>
iOS
Declare URL Handling in Info.plist
In ios/<your_project>/Info.plist, add the matching redirect URI.
Skip this part if you don't need support for "Login with WeChat".
Alternatively, use any popular deep-linking library then implement code to forward the deep link to our SDK in the JavaScript side for your React Native app.
To handle WeChat deep links, in AppDelegate.m, add the following code snippet:
Next, add the Logout button and call the logout() method from onPress. Add the button to the return statement for App() just below <Text style={{paddingTop: 50, paddingBottom: 16}}> Welcome User</Text> :
<Button onPress={logout} title="Logout" />
Save your code and run the app. Click the Logout button and the user should be logged out.
Step 8: Show User Info
The Authgear SDK includes a fetchUserInfo() method that returns details such as user ID, email, phone number, etc about the current user.
In this step, we'll add a Show User Info button to our app. This button will call the fetchUserInfo() to demonstrate how the method works.
Add a showUserInfo() method to your App() function just below the logout() method:
Now run your app and you should be able to access the User Settings page when you click on the User Settings button.
Additional Actions
Get the Logged-In State
When you start launching the application. You may want to know if the user has logged in. (e.g. Show users the login page if they haven't logged in).
The sessionState reflects the user logged-in state in the SDK local state. That means even if the sessionState is AUTHENTICATED, the session may be invalid if it is revoked remotely. Hence, after initializing the Authgear SDK, call fetchUserInfo to update the sessionState as soon as it is proper to do so. We demonstrated this in our example app using the postConfigure() method.
// After authgear.configure, it only reflect SDK local state.
// value can be NO_SESSION or AUTHENTICATED
let sessionState = authgear.sessionState;
if (sessionState === "AUTHENTICATED") {
authgear
.fetchUserInfo()
.then((userInfo) => {
// sessionState is now up to date
})
.catch((e) => {
// sessionState is now up to date
// it will change to NO_SESSION if the session is invalid
});
}
The value of sessionState can be UNKNOWN, NO_SESSION or AUTHENTICATED. Initially, the sessionState is UNKNOWN. After a call to authgear.configure(), the session state would become AUTHENTICATED if a previous session was found, or NO_SESSION if such session was not found.
Using the Access Token in HTTP Requests
To include the access token in the HTTP requests to your application server, there are two ways to achieve this.
Option 1: Using fetch function provided by Authgear SDK
Authgear SDK provides the fetch function for you to call your application server. The fetch function will include the Authorization header in your application request, and handle refresh access token automatically. authgear.fetch implement fetch.
You can access the access token through authgear.accessToken. Call refreshAccessTokenIfNeeded() every time before using the access token. The refreshAccessTokenIfNeeded() function will check and make the network call to refresh the access token only if it has expired.
Include the access token in the Authorization header of your application request.
authgear
.refreshAccessTokenIfNeeded()
.then(() => {
// access token is ready to use
// accessToken can be string or undefined
// it will be empty if user is not logged in or session is invalid
const accessToken = authgear.accessToken;
// include Authorization header in your application request
const headers = {
Authorization: `Bearer ${accessToken}`
};
});