Configuring React Native apps for OIDC sign-on
PingOne PingOne Advanced Identity Cloud PingAM OIDC-compliant servers React Native
You can configure your React Native apps to use your authorization server’s UI, or your own web application, for sign-on requests.
When a user attempts to sign on to your app it redirects them to the central sign-on UI. After the user authenticates, the authorization server redirects them back to your application.
Changes to authentication journeys or flows on your authorization server are available to all your apps that use the OIDC sign-on method, without the need to rebuild or redistribute the app. Likewise, any rebranding applied to your central sign-on UI is reflected immediately in your client apps.
Your app doesn’t need to access user credentials directly, just the result of the authentication from the server, usually an access token.
To configure a React Native app to perform OIDC sign-on, complete each of the following steps:
Optionally, you can also customize browser behavior for the sign-on flow.
Before you begin
You need to prepare your server for OIDC sign-on. Select your server from the options below and complete the tasks before proceeding to configure your application.
-
PingOne
-
Advanced Identity Cloud
-
PingAM
This tutorial requires you to configure your PingOne server as follows:
Task 1. Create a demo user
The samples and tutorials in this documentation often require that you have an identity set up so that you can test authentication.
To create a demo user in PingOne, follow these steps:
-
Log in to your PingOne administration console.
-
In the left panel, navigate to Directory > Users.
-
Next to the Users label, click the plus icon ().
PingOne displays the Add User panel.
-
Enter the following details:
-
Given Name =
Demo -
Family Name =
User -
Username =
demo -
Email =
demo.user@example.com -
Population =
Default -
Password =
Ch4ng3it!
-
-
Click Save.
Task 2. Register a public OAuth 2.0 client
To register a public OAuth 2.0 client application in PingOne for use with the Orchestration SDKs for Android and iOS, follow these steps:
-
Log in to your PingOne administration console.
-
In the left panel, navigate to Applications > Applications.
-
Next to the Applications label, click the plus icon ().
PingOne displays the Add Application panel.
-
In Application Name, enter a name for the profile, for example
sdkNativeClient -
Select Native as the Application Type, and then click Save.
-
On the Configuration tab, click the pencil icon ().
-
In Grant Type, select the following values:
Authorization CodeRefresh Token -
In Redirect URIs, enter the following values:
org.forgerock.oidc://oauth2redirect -
In Token Endpoint Authentication Method, select
None. -
Click Save.
-
-
On the Resources tab, next to Allowed Scopes, click the pencil icon ().
-
In Scopes, select the following values:
emailphoneprofileThe openidscope is selected by default.
-
-
Optionally, on the Policies tab, click the pencil icon () to select the authentication policies for the application.
Applications that have no authentication policy assignments use the environment’s default authentication policy to authenticate users.
If you have a DaVinci license, you can select PingOne policies or DaVinci Flow policies, but not both. If you do not have a DaVinci license, the page only displays PingOne policies.
To use a PingOne policy:
-
Click Add policies and then select the policies that you want to apply to the application.
-
Click Save.
PingOne applies the policies in the order in which they appear in the list. PingOne evaluates the first policy in the list first. If the requirements are not met, PingOne moves to the next one.
For more information, see Authentication policies for applications.
To use a DaVinci Flow policy:
-
You must clear all PingOne policies. Click Deselect all PingOne Policies.
-
In the confirmation message, click Continue.
-
On the DaVinci Policies tab, select the policies that you want to apply to the application.
-
Click Save.
PingOne applies the first policy in the list.
-
-
Click Save.
-
Enable the OAuth 2.0 client application by using the toggle next to its name:
Figure 1. Enable the application using the toggle.
The application is now configured to accept client connections from and issue OAuth 2.0 tokens to the Android and iOS PingOne example applications and tutorials covered by this documentation.
This tutorial requires you to configure your PingOne Advanced Identity Cloud tenant as follows:
Task 1. Create a demo user
The samples and tutorials in this documentation often require that you have an identity set up so that you can test authentication.
To create a demo user in PingOne Advanced Identity Cloud, follow these steps:
-
Log in to your PingOne Advanced Identity Cloud tenant.
-
In the left panel, click Identities > Manage.
-
Click New Alpha realm - User.
-
Enter the following details:
-
Username =
demo -
First Name =
Demo -
Last Name =
User -
Email Address =
demo.user@example.com -
Password =
Ch4ng3it!
-
-
Click Save.
Task 2. Register a public OAuth 2.0 client
Public clients do not use a client secret to obtain tokens because they are unable to keep them hidden. The Orchestration SDKs commonly use this type of client to obtain tokens, as they cannot guarantee safekeeping of the client credentials in a browser or on a mobile device.
To register a public OAuth 2.0 client application for use with the SDKs in PingOne Advanced Identity Cloud, follow these steps:
-
Log in to your PingOne Advanced Identity Cloud tenant.
-
In the left panel, click Applications.
-
Click Custom Application.
-
Select OIDC - OpenId Connect as the sign-in method, and then click Next.
-
Select Native / SPA as the application type, and then click Next.
-
In Name, enter a name for the application, such as
Public SDK Client. -
In Owners, select a user that is responsible for maintaining the application, and then click Next.
When trying out the SDKs, you could select the demouser you created previously. -
In Client ID, enter
sdkPublicClient -
Select Configure for SDK Sample Apps.
-
Click Create Application.
PingOne Advanced Identity Cloud creates the application and displays the details screen.
-
On the Sign On tab:
-
In Sign-In URLs, ensure the following values appear, or add them if they don’t:
org.forgerock.oidc://oauth2redirectAlso add any other domains where you host SDK applications. -
In Grant Types, ensure the following values appear:
Authorization CodeRefresh Token -
In Scopes, ensure the following values appear:
openid profile email address
-
-
Click Show advanced settings, and on the Authentication tab, confirm the following properties:
-
In Token Endpoint Authentication Method, select
none. -
In Client Type, select
Public. -
Enable the Implied Consent property.
-
-
Click Save.
The application is now configured to accept client connections from and issue OAuth 2.0 tokens to the example applications and tutorials covered by this documentation.
Task 3. Configure the OAuth 2.0 provider
The provider specifies the supported OAuth 2.0 configuration options for a realm.
To ensure the PingOne Advanced Identity Cloud OAuth 2.0 provider service is configured for use with the Orchestration SDKs, follow these steps:
-
In your PingOne Advanced Identity Cloud tenant, navigate to Native Consoles > Access Management.
-
In the left panel, click Services.
-
In the list of services, click OAuth2 Provider.
-
On the Core tab, ensure Issue Refresh Tokens is enabled.
-
On the Consent tab, ensure Allow Clients to Skip Consent is enabled.
-
Click Save Changes.
This tutorial requires you to configure your PingAM server as follows:
Task 1. Create a demo user
The samples and tutorials in this documentation often require that you have an identity set up so that you can test authentication.
To create a demo user in PingAM, follow these steps:
-
Log in to the PingAM admin UI as an administrator.
-
Navigate to Identities, and then click Add Identity.
-
Enter the following details:
-
User ID =
demo -
Password =
Ch4ng3it! -
Email Address =
demo.user@example.com
-
-
Click Create.
Task 2. Register a public OAuth 2.0 client
Public clients do not use a client secret to obtain tokens because they are unable to keep them hidden. The Orchestration SDKs commonly use this type of client to obtain tokens, as they cannot guarantee safekeeping of the client credentials in a browser or on a mobile device.
To register a public OAuth 2.0 client application for use with the SDKs in AM, follow these steps:
-
Log in to the PingAM admin UI as an administrator.
-
Navigate to Applications > OAuth 2.0 > Clients, and then click Add Client.
-
In Client ID, enter
sdkPublicClient. -
Leave Client secret empty.
-
In Redirection URIs, enter the following values:
org.forgerock.oidc://oauth2redirectAlso add any other domains where you will be hosting SDK applications. -
In Scopes, enter the following values:
openid profile email address -
Click Create.
PingAM creates the new OAuth 2.0 client, and displays the properties for further configuration.
-
On the Core tab:
-
In Client type, select
Public. -
Disable Allow wildcard ports in redirect URIs.
-
Click Save Changes.
-
-
On the Advanced tab:
-
In Grant Types, enter the following values:
Authorization Code Refresh Token -
In Token Endpoint Authentication Method, select
None. -
Enable the Implied consent property.
-
-
Click Save Changes.
Task 3. Configure the OAuth 2.0 provider
The provider specifies the supported OAuth 2.0 configuration options for a realm.
To ensure the PingAM OAuth 2.0 provider service is configured for use with the Orchestration SDKs, follow these steps:
-
Log in to the PingAM admin UI as an administrator.
-
In the left panel, click Services.
-
In the list of services, click OAuth2 Provider.
-
On the Core tab, ensure Issue Refresh Tokens is enabled.
-
On the Consent tab, ensure Allow Clients to Skip Consent is enabled.
-
Click Save Changes.
Step 1. Configuring your app to handle redirects
After completing authentication in the browser, the server redirects the user back to your application, by using the value of the redirectUri parameter.
The Orchestration SDK for React Native uses a custom scheme redirect URI to receive this redirect. Using this method, your redirect URI will resemble the following:
org.forgerock.oidc://oauth2redirect
To configure a custom scheme in a React Native application, perform the following steps:
- Android
-
Add the custom scheme your app will use to the
android/app/build.gradlefile:android { defaultConfig { manifestPlaceholders["appRedirectUriScheme"] = "org.forgerock.oidc" } }The custom scheme consists of the string before the colon (
:) character in the URI.Add an intent filter for
com.pingidentity.browser.CustomTabActivitytoandroid/app/src/main/AndroidManifest.xml, using theappRedirectUriSchemeplaceholder and the host segment of your redirect URI:<activity android:name="com.pingidentity.browser.CustomTabActivity" android:exported="true" android:launchMode="singleTop"> <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:scheme="${appRedirectUriScheme}" android:host="oauth2redirect" /> </intent-filter> </activity> - iOS
-
In Xcode, in the Project Navigator, double-click your application to open the Project pane.
On the Info tab, in the URL Types panel, configure your custom URL scheme:
Alternatively, add the entry directly to
ios/PingSampleApp/Info.plist:<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleTypeRole</key> <string>Editor</string> <key>CFBundleURLName</key> <string>oauth2redirect</string> <key>CFBundleURLSchemes</key> <array> <string>org.forgerock.oidc</string> </array> </dict> </array>
Add the custom URL scheme to the Redirect URIs property of your OAuth 2.0 client.
|
In an Advanced Identity Cloud tenant, enter redirect URIs in the Sign-in URLs field, in the General Settings pane. |
Step 2. Installing modules
For OIDC sign-on, install the OIDC module for React Native, and its dependency, the Core module:
-
yarn
-
npm
yarn add @ping-identity/rn-core
yarn add @ping-identity/rn-oidc
npm install @ping-identity/rn-core
npm install @ping-identity/rn-oidc
After installation, run pod install in your ios/ directory to link the native dependencies on iOS:
cd ios && pod install
Optionally, install the Storage, Logger, and Browser modules to customize token storage, logging, and browser behavior:
-
yarn
-
npm
yarn add @ping-identity/rn-storage
yarn add @ping-identity/rn-logger
yarn add @ping-identity/rn-browser
npm install @ping-identity/rn-storage
npm install @ping-identity/rn-logger
npm install @ping-identity/rn-browser
|
The OIDC module already bundles the browser components it needs to perform the authorize and logout flows. Install rn-browser only when you want to explicitly customize Custom Tabs or Auth Tabs behavior, as described in Customizing browser behavior. |
Step 3. Configuring connection properties
Configure the oidc module to connect to your OpenID Connect 1.0-compliant authorization server, by calling createOidcClient():
import { createOidcClient } from '@ping-identity/rn-oidc';
const oidcClient = createOidcClient({
clientId: '6c7eb89a-66e9-ab12-cd34-eeaf795650b2',
discoveryEndpoint: 'https://auth.pingone.com/3072206d-c6ce-ch15-m0nd-f87e972c7cc3/as/.well-known/openid-configuration',
redirectUri: 'org.forgerock.oidc://oauth2redirect',
scopes: ['openid', 'email', 'address', 'profile'],
});
Update the following properties with values that match your environment:
- clientId
-
The client ID from your OAuth 2.0 application.
For example,
6c7eb89a-66e9-ab12-cd34-eeaf795650b2 - discoveryEndpoint
-
The
.well-knownendpoint from your OAuth 2.0 application.How do I find my PingOne .well-known URL?
To find the
.well-knownendpoint for an OAuth 2.0 client in PingOne:-
Log in to your PingOne administration console.
-
Go to Applications > Applications, and then select your OAuth 2.0 client.
For example, sdkPublicClient.
-
On the Overview tab, expand the Connection Details section, and then copy the OIDC Discovery Endpoint value.
How do I find my PingOne Advanced Identity Cloud
.well-knownURL?You can view the
.well-knownendpoint for an OAuth 2.0 client in the PingOne Advanced Identity Cloud admin console:-
Log in to your PingOne Advanced Identity Cloud administration console.
-
Click Applications, and then select the OAuth 2.0 client you created earlier. For example, sdkPublicClient.
-
On the Sign On tab, in the Client Credentials section, copy the Discovery URI value.
For example,
https://openam-forgerock-sdks.forgeblocks.com/am/oauth2/alpha/.well-known/openid-configuration
If you are using a custom domain, your
.well-knownis formed as follows:https://<custom-domain-fqdn>/.well-known/openid-configurationLearn more in Access OIDC configuration discovery endpoint.
How do I find my PingAM
.well-knownURL?To form the
.well-knownURL for an PingAM server, concatenate the following information into a single URL:-
The base URL of the PingAM component of your deployment, including the port number and deployment path.
For example,
https://openam.example.com:8443/openam -
The string
/oauth2 -
The hierarchy of the realm that contains the OAuth 2.0 client.
You must specify the entire hierarchy of the realm, starting at the Top Level Realm. Prefix each realm in the hierarchy with the
realms/keyword.For example,
/realms/root/realms/customersIf you omit the realm hierarchy, the top level
ROOTrealm is used by default. -
The string
/.well-known/openid-configuration
For example,
https://auth.pingone.com/3072206d-c6ce-ch15-m0nd-f87e972c7cc3/as/.well-known/openid-configuration -
- redirectUri
-
The redirect URI as configured in the OAuth 2.0 client profile.
This value must exactly match one of the values configured in your OAuth 2.0 client.
For example,
org.forgerock.oidc://oauth2redirect - scopes
-
The scopes you added to your OAuth 2.0 application.
For example,
'openid', 'email', 'address', 'profile'
You can pass optional OAuth 2.0 parameters into the configuration to affect the OAuth 2.0 flow on the server.
const oidcClient = createOidcClient({
clientId: '6c7eb89a-66e9-ab12-cd34-eeaf795650b2',
discoveryEndpoint: 'https://auth.pingone.com/3072206d-c6ce-ch15-m0nd-f87e972c7cc3/as/.well-known/openid-configuration',
redirectUri: 'org.forgerock.oidc://oauth2redirect',
scopes: ['openid', 'email', 'address', 'profile'],
acrValues: 'Single_Factor%20Multi_Factor',
loginHint: 'demo.user@example.com',
additionalParameters: { myCustomParam: 'myCustomValue' },
});
For example, you can add the following parameters:
- acrValues
-
An optional space-separated list of Authentication Context Class Reference (
acr) values, in order of preference.The server can use these values to help determine how the user should be authenticated.
For example, you can specify a DaVinci flow policy ID, or PingOne policy names to request that PingOne follows a particular path to authenticate the user.
- loginHint
-
An optional string that lets the server know what identifier the user might use to authenticate with.
The server can use this to pre-populate a sign-on form, or to customize the UI to match a particular brand or organization.
- additionalParameters
-
Add any additional key-value query parameters your environment might require to complete an OAuth 2.0 flow.
Learn more about OAuth 2.0 authentication request parameters in Authentication Request, in the OpenID Connect Core 1.0 specification.
Configuring token storage
Optionally, customize how the module stores tokens on the device by configuring the Storage module, and passing the resulting handle into the OIDC client configuration:
import { CacheStrategy, configureOidcStorage } from '@ping-identity/rn-storage';
import { createOidcClient } from '@ping-identity/rn-oidc';
const oidcStorage = configureOidcStorage({
android: {
fileName: 'ping-oidc',
keyAlias: 'ping-oidc',
strongBoxPreferred: true,
cacheStrategy: CacheStrategy.CACHE_ON_FAILURE,
},
ios: {
account: 'com.example.app.oidc',
encryptor: true,
cacheable: true,
},
});
const oidcClient = createOidcClient({
clientId: '6c7eb89a-66e9-ab12-cd34-eeaf795650b2',
discoveryEndpoint: 'https://auth.pingone.com/3072206d-c6ce-ch15-m0nd-f87e972c7cc3/as/.well-known/openid-configuration',
redirectUri: 'org.forgerock.oidc://oauth2redirect',
scopes: ['openid', 'email', 'address', 'profile'],
storage: oidcStorage,
});
If you don’t provide a storage configuration, the module uses its default native storage settings.
Configuring logging
Optionally, pass a logger instance, created with the Logger module, into the logger property to capture diagnostic output from the OIDC client:
import { logger } from '@ping-identity/rn-logger';
import { createOidcClient } from '@ping-identity/rn-oidc';
const log = logger({ level: 'debug' });
const oidcClient = createOidcClient({
clientId: '6c7eb89a-66e9-ab12-cd34-eeaf795650b2',
discoveryEndpoint: 'https://auth.pingone.com/3072206d-c6ce-ch15-m0nd-f87e972c7cc3/as/.well-known/openid-configuration',
redirectUri: 'org.forgerock.oidc://oauth2redirect',
scopes: ['openid', 'email', 'address', 'profile'],
logger: log,
});
Learn more in Configuring logging in React Native.
Step 4. Starting the OAuth 2.0 flow
Create a web-capable client by passing your OIDC client into createOidcWebClient(), then call authorize() to launch the browser and start the OAuth 2.0 flow:
import { createOidcWebClient } from '@ping-identity/rn-oidc';
const oidcWebClient = createOidcWebClient(oidcClient);
const result = await oidcWebClient.authorize();
// result: { type: 'success' } | { type: 'cancel' }
|
You can inject or override OAuth 2.0 parameters when starting the OAuth 2.0 flow, by passing options to Adding parameters when using authorize()
|
Using the React provider and hook
If you’re using React components, you can use OidcProvider and useOidc() instead of calling the client methods directly. OidcProvider shares authentication state, such as the authenticated user and any errors, across every screen that calls useOidc(), so you don’t need to duplicate state management in each screen.
import { OidcProvider, useOidc } from '@ping-identity/rn-oidc';
function App(): React.ReactElement {
return (
<OidcProvider client={oidcWebClient}>
<OidcScreen />
</OidcProvider>
);
}
function OidcScreen(): React.ReactElement {
const [state, actions] = useOidc();
const onLogin = async (): Promise<void> ⇒ {
await actions.authorize();
};
return <></>;
}
state exposes isAuthenticated, user, isLoading, and error.
actions exposes authorize(), token(), refresh(), userinfo(), revoke(), logout(), and clear().
If you only need OIDC sign-on in a single screen, you can skip the provider and pass the client directly to the hook: useOidc(oidcWebClient).
Step 5. Obtaining an Access Token
After successfully starting the OAuth 2.0 flow and authenticating the user, the module exchanges the authorization code for tokens automatically.
To obtain those tokens, retrieve the authenticated user object by calling user(), and then call token() on the returned object:
const user = await oidcWebClient.user();
if (user) {
const tokens = await user.token();
console.log('Access token:', tokens?.accessToken);
}
user() returns null if no active session exists.
You can also call token() directly on the base client (without launching a browser), which is useful for headless token operations:
const tokens = await oidcClient.token();
To exchange the current refresh token for a new set of tokens, call refresh():
const tokens = await user.refresh();
Step 6. Obtaining user info
To fetch current user claims from the OIDC /userinfo endpoint, call userinfo() on the user object:
const profile = await user.userinfo(false);
Pass false to force a fresh network request, or true, the default, to return a cached value, if one is available.
Step 7. Revoking tokens and signing out
You can call the following methods on your user object to revoke OAuth 2.0 tokens, and sign the user out from the server:
user.revoke()-
Revokes the OAuth 2.0 tokens on the server, and deletes them from storage.
user.logout()-
Removes any session tokens the user may have, and contacts the server to end the user’s session.
Customizing browser behavior
The OIDC module uses Auth Tabs on Android where possible, and falls back to Custom Tabs if not supported by the device. On iOS, the module uses an ASWebAuthenticationSession by default.
Each platform ignores the other’s browser configuration. The android options in configureBrowser() have no effect on iOS, and the ios property has no effect on Android.
Android
To customize Android Custom Tabs and Auth Tabs globally, install the Browser module and call configureBrowser() once, before calling authorize():
import { configureBrowser } from '@ping-identity/rn-browser';
configureBrowser({
android: {
customTabs: {
showTitle: false,
urlBarHidingEnabled: true,
colorScheme: 'system',
},
authTabs: {
ephemeral: true,
colorScheme: 'dark',
toolbarColor: '#0B3D91',
},
},
});
customTabs-
Configuration used when the module falls back to Custom Tabs.
showTitle-
Show or hide the page title. Defaults to showing the title.
urlBarHidingEnabled-
Allow the URL bar to hide while scrolling.
toolbarColor-
Override the toolbar color.
colorScheme-
One of
system,light, ordark.
authTabs-
Configuration used when the module uses Auth Tabs.
ephemeral-
Prefer ephemeral browsing, where supported.
colorScheme-
One of
system,light, ordark. toolbarColor-
Override the toolbar color.
navigationBarColor-
Override the navigation bar color.
iOS
Customize the browser iOS uses for the OIDC sign-on flow by adding an ios property to the client configuration:
const oidcClient = createOidcClient({
clientId: '6c7eb89a-66e9-ab12-cd34-eeaf795650b2',
discoveryEndpoint: 'https://auth.pingone.com/3072206d-c6ce-ch15-m0nd-f87e972c7cc3/as/.well-known/openid-configuration',
redirectUri: 'org.forgerock.oidc://oauth2redirect',
scopes: ['openid', 'email', 'address', 'profile'],
ios: {
browserType: 'authSession',
},
});
Each browser type has different characteristics, which make them suitable to different scenarios, as outlined in this table:
| Browser type | Characteristics |
|---|---|
|
Opens a web authentication session browser. Designed specifically for authentication sessions, however it prompts the user before opening the browser with a modal that asks them to confirm the domain is allowed to authenticate them. This is the default option in the Orchestration SDK for iOS. |
|
Opens a web authentication session browser, but enables the This browser type does not prompt the user before opening the browser with a modal. The difference between this and When is
|
|
Opens the installed browser that is marked as the default by the user. Often Safari. The browser opens without any interaction from the user. However, the browser does display a modal when returning to your application. |
|
Opens a Safari view controller browser. Your client app is not able to interact with the pages in the The view controller opens within your app without any interaction from the user. As the user does not leave your app, the view controller does not need to display a warning modal when authentication is complete and control returns to your application. |