• Stars
    star
    432
  • Rank 97,255 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 8 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

React Native toolkit for Auth0 API

react-native-auth0

Build Status NPM version Coverage License Downloads FOSSA Status

πŸ“š Documentation β€’ πŸš€ Getting Started β€’ ⏭️ Next Steps β€’ ❓ FAQs β€’ ❓ Feedback

Documentation

Important Notices

Version 2.9.0 introduced a breaking change to the Android configuration. Previously it was required to add an intent filter in the definition of the Activity that receives the authentication result, and to use the singleTask launchMode in that activity. Now both the intent filter and the launch mode must be removed and instead you need to add a couple of manifest placeholders. Check out the Android section for more details.

Getting Started

Requirements

This SDK targets apps that are using React Native SDK version 0.60.5 and up. If you're using an older React Native version, see the compatibility matrix below.

Compatibility Matrix

This SDK attempts to follow semver in a best-effort basis, but React Native is still making releases that eventually include breaking changes on it making this approach difficult for any React Native library module. Use the table below to find the version that best suites your application.

React Native SDK Auth0 SDK
v0.65.0 v2.11.0
v0.62.2 v2.5.0
v0.60.5 v2.0.0
v0.59.0 or lower v1.6.0

The contents of previous release can be found on the branch v1.

Installation

First install the native library module:

With npm

$ npm install react-native-auth0 --save

With Yarn

$ yarn add react-native-auth0

Then, you need to run the following command to install the ios app pods with Cocoapods. That will auto-link the iOS library:

$ cd ios && pod install

Configure the SDK

You need make your Android, iOS or Expo applications aware that an authentication result will be received from the browser. This SDK makes use of the Android's Package Name and its analogous iOS's Product Bundle Identifier to generate the redirect URL. Each platform has its own set of instructions.

Android

Before version 2.9.0, this SDK required you to add an intent filter to the Activity on which you're going to receive the authentication result, and to use the singleTask launchMode in that activity. To migrate your app to version 2.9.0+, remove both and continue with the instructions below. You can also check out a sample migration diff here.

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: "YOUR_AUTH0_DOMAIN", auth0Scheme: "${applicationId}"]
    }
    ...
}

The auth0Domain value must be replaced with your Auth0 domain value. So if you have samples.auth0.com as your Auth0 domain you would have a configuration like the following:

android {
    defaultConfig {
        manifestPlaceholders = [auth0Domain: "samples.auth0.com", auth0Scheme: "${applicationId}"]
    }
    ...
}

The applicationId value will be auto-replaced at 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.

Note that if your Android application is using product flavors, you might need to specify different manifest placeholders for each flavor.

If you use a value other than applicationId in auth0Scheme you will also need to pass it as the customScheme option parameter of the authorize and clearSession methods.

Take note of this value as you'll be requiring it to define the callback URLs below.

For more info please read the React Native docs.

Skipping the Web Authentication setup

If you don't plan to use Web Authentication, you will notice that the compiler will still prompt you to provide the manifestPlaceholders values, since the RedirectActivity included in this library will require them, and the Gradle tasks won't be able to run without them.

Re-declare the activity manually with tools:node="remove" in your app's Android Manifest in order to make the manifest merger remove it from the final manifest file. Additionally, one more unused activity can be removed from the final APK by using the same process. A complete snippet to achieve this is:

<activity
    android:name="com.auth0.react.AuthenticationActivity"
    tools:node="remove"/>
<!-- Optional: Remove RedirectActivity -->
<activity
    android:name="com.auth0.react.RedirectActivity"
    tools:node="remove"/>

iOS

Inside the ios folder find the file AppDelegate.[swift|m] add the following to it:

#import <React/RCTLinkingManager.h>

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

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

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

and then below it register a URL type entry using the value of CFBundleIdentifier as the value for 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 is generated using the React Native CLI, the default value of $(PRODUCT_BUNDLE_IDENTIFIER) matches org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier). Take note of this value as you'll be requiring it to define the callback URLs below. If desired, you can change its value using XCode in the following way:

  • Open the ios/TestApp.xcodeproj file replacing 'TestApp' with the name of your app or run xed ios from a Terminal.
  • Open your project's or desired target's Build Settings tab and on the search bar at the right type "Product Bundle Identifier".
  • Replace the Product Bundle Identifier value with your desired application's bundle identifier name (e.g. com.example.app).
  • If you've changed the project wide settings, make sure the same were applied to each of the targets your app has.

If you use a value other than $(PRODUCT_BUNDLE_IDENTIFIER) in the CFBundleURLSchemes field of the Info.plist you will also need to pass it as the customScheme option parameter of the authorize and clearSession methods.

For more info please read the React Native docs.

Expo

⚠️ This SDK is not compatible with "Expo Go" app because of custom native code. It is compatible with Custom Dev Client and EAS builds

To use the SDK with Expo, configure the app at build time by providing the domain and the customScheme values through the Config Plugin. To do this, add the following snippet to app.json or app.config.js:

{
  "expo": {
    ...
    "plugins": [
      [
        "react-native-auth0",
        {
          "domain": "YOUR_AUTH0_DOMAIN",
          "customScheme": "YOUR_CUSTOM_SCHEME"
        }
      ]
    ]
  }
}
API Description
domain Mandatory: Provide the Auth0 domain that can be found at the Application Settings
customScheme Mandatory: Custom scheme to build the callback URL with. The value provided here should be passed to the customScheme option parameter of the authorize and clearSession methods. The custom scheme should be a unique, all lowercase value with no special characters (For example: auth0.YOUR_APP_PACKAGE_NAME_OR_BUNDLE_IDENTIFIER).

Now you can run the application using expo run:android or expo run:ios.

Callback URL(s)

Callback URLs are the URLs that Auth0 invokes after the authentication process. Auth0 routes your application back to this URL and appends additional parameters to it, including a token. Since callback URLs can be manipulated, you will need to add this URL to your Application's Allowed Callback URLs for security. This will enable Auth0 to recognize these URLs as valid. If omitted, authentication will not be successful.

On the Android platform this URL is case-sensitive. Because of that, this SDK will auto convert the Bundle Identifier (iOS) and Application ID (Android) values to lowercase in order to build the Callback URL with them. If any of these values contains uppercase characters a warning message will be printed in the console. Make sure to check that the right Callback URL is whitelisted in the Auth0 dashboard or the browser will not route succesfully back to your application.

Go to the Auth0 Dashboard, select your application and make sure that Allowed Callback URLs contains the URLs defined below.

If in addition you plan to use the log out method, you must also add these URLs to the Allowed Logout URLs.

Android

{APP_PACKAGE_NAME_OR_CUSTOM_SCHEME}://{AUTH0_DOMAIN}/android/{APP_PACKAGE_NAME}/callback

Make sure to replace {APP_PACKAGE_NAME_OR_CUSTOM_SCHEME} and {AUTH0_DOMAIN} with the actual values for your application. The {APP_PACKAGE_NAME_OR_CUSTOM_SCHEME} value provided should be all lower case.

iOS

{BUNDLE_IDENTIFIER_OR_CUSTOM_SCHEME}://{AUTH0_DOMAIN}/ios/{BUNDLE_IDENTIFIER}/callback

Make sure to replace {BUNDLE_IDENTIFIER_OR_CUSTOM_SCHEME} and {AUTH0_DOMAIN} with the actual values for your application. The {BUNDLE_IDENTIFIER_OR_CUSTOM_SCHEME} value provided should be all lower case.

Next Steps

This SDK is OIDC compliant. To ensure OIDC compliant responses from the Auth0 servers enable the OIDC Conformant switch in your Auth0 dashboard under Application / Settings / Advanced OAuth. For more information please check this documentation.

Web Authentication

The SDK exports a React hook as the primary interface for performing web authentication through the browser using Auth0 Universal Login.

Use the methods from the useAuth0 hook to implement login, logout, and to retrieve details about the authenticated user.

See the API Documentation for full details on the useAuth0 hook.

First, import the Auth0Provider component and wrap it around your application. Provide the domain and clientId values as given to you when setting up your Auth0 app in the dashboard:

import {Auth0Provider} from 'react-native-auth0';

const App = () => {
  return (
    <Auth0Provider domain="YOUR_AUTH0_DOMAIN" clientId="YOUR_AUTH0_CLIENT_ID">
      {/* YOUR APP */}
    </Auth0Provider>
  );
};

export default App;
Using the `Auth0` class

If you're not using React Hooks, you can simply instantiate the Auth0 class:

import Auth0 from 'react-native-auth0';

const auth0 = new Auth0({
  domain: 'YOUR_AUTH0_DOMAIN',
  clientId: 'YOUR_AUTH0_CLIENT_ID',
});

Then import the hook into a component where you want to get access to the properties and methods for integrating with Auth0:

import {useAuth0} from 'react-native-auth0';

Login

Use the authorize method to redirect the user to the Auth0 Universal Login page for authentication.

  • The isLoading property is set to true once the authentication state of the user is known to the SDK.
  • The user property is populated with details about the authenticated user. If user is null, no user is currently authenticated.
  • The error property is populated if any error occurs.
const Component = () => {
  const {authorize, user, isLoading, error} = useAuth0();

  const login = async () => {
    await clearSession(); // clearSession({customScheme: 'CUSTOM_SCHEME') when using Expo or a custom scheme
  };

  if(isLoading) {
    return (
      <View>
        <Text>SDK is Loading</Text>
      </View>
    )
  }

  return (
    <View>
      {!user && <Button onPress={login} title="Log in" />}
      {user && <Text>Logged in as {user.name}</Text>}
      {error && <Text>{error.message}</Text>}
    </View>
  );
};
Using the `Auth0` class
auth0.webAuth
  .authorize({scope: 'openid email profile'})
  .then(credentials => console.log(credentials))
  .catch(error => console.log(error));

Web Authentication flows require a Browser application installed on the device. When no Browser is available, an error of type a0.browser_not_available will be raised via the provided callback.

SSO Alert Box (iOS)

ios-sso-alert

Check the FAQ for more information about the alert box that pops up by default when using Web Auth on iOS.

See also this blog post for a detailed overview of Single Sign-On (SSO) on iOS.

Logout

Log the user out by using the clearSession method from the useAuth0 hook.

const Component = () => {
  const {clearSession, user} = useAuth0();

  const logout = async () => {
    await clearSession(); // clearSession({customScheme: 'CUSTOM_SCHEME') when using Expo or a custom scheme
  };

  return <View>{user && <Button onPress={logout} title="Log out" />}</View>;
};
Using the `Auth0` class
auth0.webAuth.clearSession().catch(error => console.log(error));

Credentials Manager

The Credentials Manager allows you to securely store and retrieve the user's credentials. The credentials will be stored encrypted in Shared Preferences on Android, and in the Keychain on iOS.

The Auth0 class exposes the credentialsManager property for you to interact with using the API below.

πŸ’‘ If you're using Web Auth (authorize) through Hooks, you do not need to manually store the credentials after login and delete them after logout; the SDK does this automatically.

Check for stored credentials

When the users open your app, check for valid credentials. If they exist, you can retrieve them and redirect the users to the app's main flow without any additional login steps.

const isLoggedIn = await auth0.credentialsManager.hasValidCredentials();

if (isLoggedIn) {
  // Retrieve credentials and redirect to the main flow
} else {
  // Redirect to the login page
}

Retrieve stored credentials

The credentials will be automatically renewed using the refresh token, if the access token has expired. This method is thread safe.

const credentials = await auth0.credentialsManager.getCredentials();

πŸ’‘ You do not need to call credentialsManager.saveCredentials() afterward. The Credentials Manager automatically persists the renewed credentials.

Local authentication

You can enable an additional level of user authentication before retrieving credentials using the local authentication supported by the device, for example PIN or fingerprint on Android, and Face ID or Touch ID on iOS.

await auth0.credentialsManager.requireLocalAuthentication();

Check the API documentation to learn more about the available LocalAuthentication properties.

⚠️ You need a real device to test Local Authentication for iOS. Local Authentication is not available in simulators.

Credentials Manager errors

The Credentials Manager will only throw CredentialsManagerError exceptions. You can find more information in the details property of the exception.

try {
  const credentials = await auth0.credentialsManager.getCredentials();
} catch (error) {
  console.log(error);
}

Feedback

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the following:

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability Reporting

Please do not report security vulnerabilities on the public Github issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.


Auth0 Logo

Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0?

This project is licensed under the MIT license. See the LICENSE file for more info.

More Repositories

1

node-jsonwebtoken

JsonWebToken implementation for node.js http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html
JavaScript
17,054
star
2

java-jwt

Java implementation of JSON Web Token (JWT)
Java
5,403
star
3

express-jwt

connect/express middleware that validates a JsonWebToken (JWT) and set the req.user with the attributes
TypeScript
4,396
star
4

jwt-decode

Decode JWT tokens; useful for browser applications.
JavaScript
2,913
star
5

angular2-jwt

Helper library for handling JWTs in Angular apps
TypeScript
2,606
star
6

nextjs-auth0

Next.js SDK for signing in with Auth0
TypeScript
1,903
star
7

angular-jwt

Library to help you work with JWTs on AngularJS
JavaScript
1,259
star
8

lock

Auth0's signin solution
JavaScript
1,121
star
9

go-jwt-middleware

A Middleware for Go Programming Language to check for JWTs on HTTP requests
Go
978
star
10

auth0.js

Auth0 headless browser sdk
JavaScript
949
star
11

auth0-spa-js

Auth0 authentication for Single Page Applications (SPA) with PKCE
TypeScript
873
star
12

auth0-react

Auth0 SDK for React Single Page Applications (SPA)
TypeScript
820
star
13

node-jwks-rsa

A library to retrieve RSA public keys from a JWKS (JSON Web Key Set) endpoint.
JavaScript
767
star
14

node-jws

JSON Web Signatures
JavaScript
698
star
15

angular-storage

A storage library for AngularJS done right
JavaScript
644
star
16

repo-supervisor

Scan your code for security misconfiguration, search for passwords and secrets. πŸ”
JavaScript
632
star
17

node-auth0

Node.js client library for the Auth0 platform.
JavaScript
586
star
18

cosmos

πŸ”­ Auth0 Design System
JavaScript
545
star
19

JWTDecode.swift

A JWT decoder for iOS, macOS, tvOS, and watchOS
Swift
545
star
20

nginx-jwt

Lua script for Nginx that performs reverse proxy auth using JWT's
JavaScript
534
star
21

SimpleKeychain

A simple Keychain wrapper for iOS, macOS, tvOS, and watchOS
Swift
488
star
22

auth0-python

Auth0 SDK for Python
Python
445
star
23

express-openid-connect

An Express.js middleware to protect OpenID Connect web applications.
JavaScript
434
star
24

JWTDecode.Android

A library to help you decode JWTs for Android
Java
428
star
25

docs

Auth0 documentation
JavaScript
364
star
26

auth0-PHP

PHP SDK for Auth0 Authentication and Management APIs.
PHP
355
star
27

wt-cli

Webtask CLI - all you need is code
JavaScript
322
star
28

auth0.net

.NET client for the Auth0 Authentication & Management APIs.
C#
296
star
29

passport-auth0

Auth0 authentication strategy for Passport.js
JavaScript
283
star
30

rules

Rules are code snippets written in JavaScript that are executed as part of the authentication pipeline in Auth0
JavaScript
283
star
31

react-native-lock

[DEPRECATED] A wrapper of Lock to use with React Native (iOS & Android)
Java
277
star
32

Auth0.swift

Auth0 SDK for Apple platforms
Swift
275
star
33

auth0-java

Java client library for the Auth0 platform
Java
265
star
34

Lock.swift

A Swift & iOS framework to authenticate using Auth0 and with a Native Look & Feel
Swift
251
star
35

auth0-cli

Build, manage and test your Auth0 integrations from the command line
Go
232
star
36

auth0-deploy-cli

The Auth0 Deploy CLI is a tool that helps you manage your Auth0 tenant configuration. It integrates into your development workflows as a standalone CLI or as a node module.
JavaScript
231
star
37

laravel-auth0

Laravel SDK for Auth0 Authentication and Management APIs.
PHP
224
star
38

ruby-auth0

Ruby toolkit for Auth0 API
Ruby
189
star
39

cxn

cXn: extensible open-source CDN
Ruby
178
star
40

jwks-rsa-java

Java
178
star
41

passport-windowsauth

Windows Authentication strategy for Passport.js
JavaScript
175
star
42

Auth0.Android

Android toolkit for Auth0 API
Kotlin
171
star
43

auth0-angular

Auth0 SDK for Angular Single Page Applications
TypeScript
167
star
44

styleguide

πŸ–Œ Conjunction of design patterns, components and resources used across our products.
Stylus
160
star
45

terraform-provider-auth0

The Auth0 Terraform Provider is the official plugin for managing Auth0 tenant configuration through the Terraform tool.
Go
155
star
46

Lock.Android

Android Library to authenticate using Auth0 and with a Native Look & Feel
Java
140
star
47

jwt-handbook-samples

JWT Handbook code samples
JavaScript
139
star
48

wordpress

WordPress Plugin for Auth0 Authentication
PHP
133
star
49

node-samlp

SAML Protocol support for node (only IdP for now)
JavaScript
129
star
50

passport-linkedin-oauth2

Passport Strategy for LinkedIn OAuth 2.0
JavaScript
115
star
51

omniauth-auth0

OmniAuth strategy to login with Auth0
Ruby
112
star
52

symfony

Symfony SDK for Auth0 Authentication and Management APIs.
PHP
110
star
53

go-auth0

Go SDK for the Auth0 Management API.
Go
107
star
54

node-odata-parser

OData query string parser for node.js.
JavaScript
106
star
55

node-jwa

JSON Web Algorithms
JavaScript
98
star
56

auth0-vue

Auth0 authentication SDK for Vue.js apps
TypeScript
95
star
57

lock-passwordless

Auth0 Lock Passwordless [DEPRECATED]
JavaScript
93
star
58

express-jwt-authz

Validate the JWT scope to authorize access to an endpoint
JavaScript
93
star
59

auth0-angular2

84
star
60

auth0-aspnetcore-authentication

SDK for integrating Auth0 in ASPNET Core
C#
82
star
61

open-source-template

A template for open source projects at Auth0
81
star
62

auth0-authorization-extension

Auth0 Extension that adds authorization features to your account
JavaScript
81
star
63

react-browserify-spa-seed

Seed / Boilerplate project to create your own SPA using React, Browserify and ReworkCSS
JavaScript
80
star
64

node-baas

Node.js implementation of Bcrypt as a micro service.
JavaScript
79
star
65

password-sheriff

Password policies made easy.
JavaScript
77
star
66

sharelock-android

Sharelock Android app
Java
76
star
67

auth0-oidc-client-net

OIDC Client for .NET Desktop and Mobile applications
C#
75
star
68

node-oauth2-jwt-bearer

Monorepo for libraries that protect Node APIs with OAuth2 Bearer JWTs
TypeScript
75
star
69

idtoken-verifier

Lightweight RSA JWT verification
JavaScript
73
star
70

ad-ldap-connector

Auth0 AD and LDAP connector
JavaScript
70
star
71

nodejs-msi

Build an MSI Windows Installer for a node.js application using WIX Toolset.
PowerShell
70
star
72

auth0-spring-security-api

Spring Security integration with Auth0 to secure your API with JWTs
Java
70
star
73

id-generator

Generates random ids with a prefix (a la Stripe)
JavaScript
66
star
74

node-saml

SAML assertion creation for node
JavaScript
65
star
75

webtask-scripts

JavaScript
61
star
76

TouchIDAuth

A library for passwordless authentication using TouchID & JWT
Objective-C
60
star
77

passport-azure-ad-oauth2

OAuth 2.0 authentication Passport strategies for Windows Azure Active Directory
JavaScript
59
star
78

spa-pkce

JavaScript
58
star
79

discourse-plugin

Discourse plugin to authenticate with auth0.
Ruby
58
star
80

auth0-multitenant-spa-api-sample

JQuery SPA + Node.js API with multi-tenant support
JavaScript
58
star
81

sandboxjs

Sandbox node.js code like a boss
JavaScript
58
star
82

multitenant-jwt-auth

This sample shows how to implement an API that authenticates using JWTs. It supports mutiple tenants and JWT blacklisting.
JavaScript
54
star
83

coreos-mongodb

CoreOS MongoDB units
52
star
84

shiny-auth0

Auth0 shiny proxy
JavaScript
51
star
85

auth0-flutter

Auth0 SDK for Flutter
Dart
49
star
86

auth0-cordova

Auth0 integration for Cordova apps
JavaScript
49
star
87

sharelock-osx

Swift
47
star
88

disyuntor

A circuit-breaker implementation for node.js
TypeScript
47
star
89

passport-wsfed-saml2

passport strategy for both WS-fed and SAML2 protocol
JavaScript
47
star
90

php-jwt-example

Php JWT example.
PHP
46
star
91

auth0-aspnet-owin

Auth0 ASP.NET 4.5 Owin/Katana Authentication Handler
JavaScript
46
star
92

webauthn.me

webauthn.me, learn more about the Web Authentication API or try the debugger.
JavaScript
43
star
93

auth0-custom-password-reset-hosted-page

An example on how to do a custom reset password hosted page.
HTML
41
star
94

magic

Auth0 Cryptography Toolkit
JavaScript
40
star
95

auth0-java-mvc-common

Contains common helper classes and api client logic that are used across our Java MVC libraries
Java
39
star
96

single-page-app-seed

A very opinionated seed for creating Single Page Apps that uses NO framework at all. Just a bunch of component libs
JavaScript
39
star
97

auth0-dotnet-templates

Auth0 Templates for .NET
C#
38
star
98

webtask-workshop

37
star
99

kbd

Styles for <kbd> tags.
HTML
37
star
100

express-oauth2-bearer

Experimental Middleware for express.js to validate access tokens.
JavaScript
36
star