npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@geniusfund/okta-react-native

v1.0.2

Published

Okta OIDC for React Native

Downloads

11

Readme

Okta React Native

npm version build status

The Okta React Native library makes it easy to add authentication to your React Native app. This library is a wrapper around Okta OIDC Android and Okta OIDC iOS.

This library follows the current best practice for native apps using:

Prerequisites

  • If you do not already have a Developer Edition Account, you can create one at https://developer.okta.com/signup/.
  • If you don't have a React Native app, or are new to React Native, please continue with the React Native CLI Quickstart guide. It will walk you through the creation of a React Native app and other application development essentials.
  • If you are developing with an Android device emulator, make sure to check out the React Native - Android Development setup instructions.

Add an OpenID Connect Client in Okta

In Okta, applications are OpenID Connect clients that can use Okta Authorization servers to authenticate users. Your Okta Org already has a default authorization server, so you just need to create an OIDC client that will use it.

  • Log into the Okta Developer Dashboard, click Applications then Add Application.
  • Choose Native as the platform, then submit the form the default values, which should look similar to this:

| Setting | Value | | ------------------- | -------------------------------------------- | | App Name | My Native App | | Login redirect URIs | com.mynativeapp:/ | | Grant Types Allowed | Authorization Code, Refresh Token |

After you have created the application there are two more values you will need to gather:

| Setting | Where to Find | | ------------- | ------------------------------------------------------------------------------ | | Client ID | In the applications list, or on the "General" tab of a specific application. | | Org URL | On the home screen of the developer dashboard, in the upper right. |

Note: As with any Okta application, make sure you assign Users or Groups to the OpenID Connect Client. Otherwise, no one can use it.

These values will be used in your React application to setup the OpenID Connect flow with Okta.

Getting started

This library is available through npm. To install it, simply add it to your project:

$ npm install @okta/okta-react-native --save
$ react-native link @okta/okta-react-native

Perform the following Manual installation steps if you're not using react-native link.

Manual installation (Optional)

iOS
  1. In XCode, in the project navigator, right click LibrariesAdd Files to [your project's name]
  2. Go to node_modules@okta/okta-react-native and add ReactNativeOktaSdkBridge.xcodeproj
  3. In XCode, in the project navigator, select your project. Add libReactNativeOktaSdkBridge.a to your project's Build PhasesLink Binary With Libraries
  4. Run your project (Cmd+R)<
Android
  1. Open up android/app/src/main/java/[...]/MainApplication.java
  • Add import com.oktareactnative.OktaSdkBridgePackage; to the imports at the top of the file
  • Add new OktaSdkBridgePackage() to the list returned by the getPackages() method
  1. Append the following lines to android/settings.gradle:
    include ':@okta/okta-react-native'
    project(':@okta/okta-react-native').projectDir = new File(rootProject.projectDir, '../node_modules/@okta/okta-react-native/android')
  2. Insert the following lines inside the dependencies block in android/app/build.gradle:
      compile project(':@okta_okta-react-native')

iOS Setup

To setup iOS, there are three steps that you must take.

  1. Make sure your iOS app's deployment target is 11.0 and above.
  2. Install Okta Open ID Connect iOS.
  3. Make sure you also configure Swift.

Set iOS Deployment Target

This library supports iOS version 11.0 and above. Go to your project -> Build settings -> iOS Deployment Target, and set it to at least version 11.0.

Install Okta Open ID Connect iOS

This library depends on the native Okta OIDC iOS library. It is not distributed as part of the React Native library to keep your dependency management consistent.

You can currently add Okta OIDC iOS through CocoaPods:

  1. CocoaPods With CocoaPods, make sure your Podfile looks like this:

    platform :ios, '11.0'
    
    target '{YourTargetName}' do
      use_frameworks!
    
      pod 'OktaOidc', '~> 3.0'
    
    end

    Then run pod install.

Swift Configuration

Since React Native uses Objective-C, and Okta React Native library is a Swift wrapper, you will need to have at least one Swift file in your iOS project for the project to compile. To add a dummy Swift file, follow the following steps:

  1. Right click on your project, then New file.
  2. Select Swift file, enter a title, and save.
  3. If prompted for a header file, it is not required to create one.
  4. Go to Build Settings, look for Swift Compiler - Language, set Swift Language Version to 4.2.

If you're getting Swift linker issues, try adding this line to your project's library search path:

  $(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)

Android Setup

For Android, there are two steps that you must take:

  1. Installing Okta Open Id Connect Android.
  2. Add a redirect scheme to your project.

Install Okta Open ID Connect Android

This library depends on the native Okta OIDC Android library. You have to add this library through Gradle. Follow the following steps:

  1. Add this line to android/build.gradle, under allprojects -> repositories.

    maven {
      url  "https://dl.bintray.com/okta/com.okta.android"
    }
  2. Make sure your minSdkVersion is 19 in android/build.gradle.

Add redirect scheme

Defining a redirect scheme to capture the authorization redirect. In android/app/build.gradle, under android -> defaultConfig, add:

manifestPlaceholders = [
  appAuthRedirectScheme: 'com.sampleapplication'
]

Usage

You will need the values from the OIDC client that you created in the previous step to set up. You will also need to know your Okta Org URL, which you can see on the home page of the Okta Developer console.

Before calling any other method, it is important that you call createConfig to set up the configuration properly on the native modules.

Importing methods would follow this pattern:

import { createConfig, signIn, signOut, getAccessToken } from '@okta/okta-react-native';

createConfig

This method will create a configured client on the native modules. Resolves true if successfully configures a client. Note: requireHardwareBackedKeyStore is a configurable setting only on android devices. If you're a developer testing on android emulators, set this field to false.

await createConfig({
  clientId: "{clientId}",
  redirectUri: "{redirectUri}",
  endSessionRedirectUri: "{endSessionRedirectUri}",
  discoveryUri: "https://{yourOktaDomain}",
  scopes: ["openid", "profile", "offline_access"],
  requireHardwareBackedKeyStore: true
});

signIn

This async method will automatically redirect users to your Okta organziation for authentication. It will an event once a user successfully signs in. Make sure your event listeners are mounted and unmounted. Note: on iOS there isn't a onCancelled event. If the sign in process is cancelled, onError will be triggered.

signIn();
Sample Usage
import { signIn, EventEmitter } from '@okta/okta-react-native';

componentDidMount() {
  this.signInSuccess = EventEmitter.addListener('signInSuccess', function(e: Event) {
    console.log(e.access_token);
    // Do something ...
  });
  this.signOutSuccess = EventEmitter.addListener('signOutSuccess', function(e: Event) {
    //...
  });
  this.onError = EventEmitter.addListener('onError', function(e: Event) {
    //...
  });
  this.onCancelled = EventEmitter.addListener('onCancelled', function(e: Event) {
    //...
  });
}

componentWillUnmount() {
  this.signInSuccess.remove();
  this.signOutSuccess.remove();
  this.onError.remove();
  this.onCancelled.remove();
}

signOut

Clear the browser session and clear the app session (stored tokens) in memory. Fires an event once a user successfully logs out. For sample usage, refer to signIn.

signOut();

isAuthenticated

Returns a promise that resolves to true if there is a valid access token or ID token. Otherwise false.

await isAuthenticated();
Sample Response

If authenticated:

{
  "authenticated": true
}

Else:

{
  "authenticated": false
}

getAccessToken

This method returns a promise that will return the access token as a string. If no access token is available (either does not exist, or expired), then the promise will be rejected.

await getAccessToken();
Sample Response

If an access token is available:

{
  "access_token": "{accessToken}"
}

getIdToken

This method returns a promise that will return the identity token as a string. The promise will be rejected if no id token is available.

await getIdToken();
Sample Response

If an id token is available:

{
  "id_token": "{idToken}"
}

getUser

Returns a promise that will fetch the most up-to-date user claims from the OpenID Connect /userinfo endpoint.

await getUser();
Sample Response

If a user is available:

{
  "sub": "00uid4BxXw6I6TV4m0g3",
  "name" :"John Doe",
  "nickname":"Jimmy",
  "given_name":"John",
  "middle_name":"James",
  "family_name":"Doe",
  "profile":"https://example.com/john.doe",
  "zoneinfo":"America/Los_Angeles",
  "locale":"en-US",
  "updated_at":1311280970,
  "email":"[email protected]",
  "email_verified":true,
  "address" : { "street_address":"123 Hollywood Blvd.", "locality":"Los Angeles", "region":"CA", "postal_code":"90210", "country":"US" },
  "phone_number":"+1 (425) 555-1212"
}

getUserFromIdToken

Returns the user claims decoded from the identity token.

await getUserFromIdToken();
Sample Response

Sample user claims:

{
  "sub": "00uid4BxXw6I6TV4m0g3", 
  "name": "John Doe", 
  "preferred_username": "[email protected]"
  "ver": 1, 
  "iss": "https://dev-example.okta.com", 
  "aud": "00uid4BxXw6I6TV4m0g3",
  "auth_time": 1561679776,
  "exp": 1561683377,
  "iat": 1561679777,
  "idp": "00uid4BxXw6I6TV4m0g3"
}

revokeAccessToken

Revoke the access token to make it inactive. Resolves true if access token has been successfully revoked.

await revokeAccessToken();

revokeIdToken

Revoke the identity token to make it inactive. Resolves true if id token has been successfully revoked.

await revokeIdToken();

revokeRefreshToken

Revoke the refresh token to make it inactive. Resolves true if refresh token has been successfully revoked.

await revokeRefreshToken();

introspectAccessToken

Introspect the access token.

await introspectAccessToken();
Sample Response

Sample responses can be found here

introspectIdToken

Introspect the id token.

await introspectIdToken();
Sample Response

Sample responses can be found here

introspectRefreshToken

Introspect the id token.

await introspectRefreshToken();
Sample Response

Sample responses can be found here

refreshTokens

Refreshes all tokens. Resolves with the refreshed tokens.

await refreshTokens();
Sample Response
{ 
  "access_token": "{accessToken}", 
  "id_token": "{idToken}", 
  "refresh_token": "refreshToken" 
}