React native bridge for AppAuth - an SDK for communicating with OAuth2 providers
See version 2.x
documentation here.
See version 1.x
documentation here.
React Native bridge for AppAuth-iOS and AppAuth-Android SDKS for communicating with OAuth 2.0 and OpenID Connect providers.
This library should support any OAuth provider that implements the OAuth2 spec.
These providers are OpenID compliant, which means you can use autodiscovery.
- Identity Server4 (Example configuration)
- Identity Server3 (Example configuration)
- Google (Example configuration)
- Okta (Example configuration)
- Keycloak (Example configuration)
- Azure Active Directory (Example configuration)
These providers implement the OAuth2 spec, but are not OpenID providers, which means you must configure the authorization and token endpoints yourself.
AppAuth is a mature OAuth client implementation that follows the best practices set out in
RFC 8252 - OAuth 2.0 for Native Apps including using
SFAuthenticationSession
and SFSafariViewController
on iOS, and
Custom Tabs on
Android. WebView
s are explicitly not supported due to the security and usability reasons
explained in Section 8.12 of RFC 8252.
AppAuth also supports the PKCE ("Pixy") extension to OAuth which was created to secure authorization codes in public clients when custom URI scheme redirects are used.
To learn more, read this short introduction to OAuth and PKCE on the Formidable blog.
See Usage for example configurations, and the included Example application for a working sample.
This is the main function to use for authentication. Invoking this function will do the whole login flow and returns the access token, refresh token and access token expiry date when successful, or it throws an error when not successful.
import { authorize } from 'react-native-app-auth';
const config = {
issuer: '<YOUR_ISSUER_URL>',
clientId: '<YOUR_CLIENT_ID>',
redirectUrl: '<YOUR_REDIRECT_URL>',
scopes: ['<YOUR_SCOPES_ARRAY>'],
};
const result = await authorize(config);
This is your configuration object for the client. The config is passed into each of the methods with optional overrides.
- issuer - (
string
) base URI of the authentication server. If noserviceConfiguration
(below) is provided, issuer is a mandatory field, so that the configuration can be fetched from the issuer's OIDC discovery endpoint. - serviceConfiguration - (
object
) you may manually configure token exchange endpoints in cases where the issuer does not support the OIDC discovery protocol, or simply to avoid an additional round trip to fetch the configuration. If noissuer
(above) is provided, the service configuration is mandatory.- authorizationEndpoint - (
string
) REQUIRED fully formed url to the OAuth authorization endpoint - tokenEndpoint - (
string
) REQUIRED fully formed url to the OAuth token exchange endpoint - revocationEndpoint - (
string
) fully formed url to the OAuth token revocation endpoint. If you want to be able to revoke a token and noissuer
is specified, this field is mandatory. - registrationEndpoint - (
string
) fully formed url to your OAuth/OpenID Connect registration endpoint. Only necessary for servers that require client registration.
- authorizationEndpoint - (
- clientId - (
string
) REQUIRED your client id on the auth server - clientSecret - (
string
) client secret to pass to token exchange requests.โ ๏ธ Read more about client secrets - redirectUrl - (
string
) REQUIRED the url that links back to your app with the auth code - scopes - (
array<string>
) the scopes for your token, e.g.['email', 'offline_access']
. - additionalParameters - (
object
) additional parameters that will be passed in the authorization request. Must be string values! E.g. settingadditionalParameters: { hello: 'world', foo: 'bar' }
would addhello=world&foo=bar
to the authorization request. - dangerouslyAllowInsecureHttpRequests - (
boolean
) ANDROID whether to allow requests over plain HTTP or with self-signed SSL certificates.โ ๏ธ Can be useful for testing against local server, should not be used in production. This setting has no effect on iOS; to enable insecure HTTP requests, add a NSExceptionAllowsInsecureHTTPLoads exception to your App Transport Security settings.
This is the result from the auth server
- accessToken - (
string
) the access token - accessTokenExpirationDate - (
string
) the token expiration date - additionalParameters - (
Object
) additional url parameters from the auth server - idToken - (
string
) the id token - refreshToken - (
string
) the refresh token - tokenType - (
string
) the token type, e.g. Bearer
This method will refresh the accessToken using the refreshToken. Some auth providers will also give you a new refreshToken
import { refresh } from 'react-native-app-auth';
const config = {
issuer: '<YOUR_ISSUER_URL>',
clientId: '<YOUR_CLIENT_ID>',
redirectUrl: '<YOUR_REDIRECT_URL>',
scopes: ['<YOUR_SCOPES_ARRAY>'],
};
const result = await refresh(config, {
refreshToken: `<REFRESH_TOKEN>`
});
This method will revoke a token. The tokenToRevoke can be either an accessToken or a refreshToken
import { revoke } from 'react-native-app-auth';
const config = {
issuer: '<YOUR_ISSUER_URL>',
clientId: '<YOUR_CLIENT_ID>',
redirectUrl: '<YOUR_REDIRECT_URL>',
scopes: ['<YOUR_SCOPES_ARRAY>'],
};
const result = await revoke(config, {
tokenToRevoke: `<TOKEN_TO_REVOKE>`
});
npm install react-native-app-auth --save
react-native link react-native-app-auth
Then follow the Setup steps to configure the native iOS and Android projects.
If you are not using react-native link
, perform the Manual installation
steps instead.
- In XCode, in the project navigator, right click
Libraries
โAdd Files to [your project's name]
- Go to
node_modules
โreact-native-app-auth
and addRNAppAuth.xcodeproj
- In XCode, in the project navigator, select your project. Add
libRNAppAuth.a
to your project'sBuild Phases
โLink Binary With Libraries
- Run your project (
Cmd+R
)<
- Open up
android/app/src/main/java/[...]/MainApplication.java
- Add
import com.reactlibrary.RNAppAuthPackage;
to the imports at the top of the file - Add
new RNAppAuthPackage()
to the list returned by thegetPackages()
method
- Append the following lines to
android/settings.gradle
:include ':react-native-app-auth' project(':react-native-app-auth').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-app-auth/android')
- Insert the following lines inside the dependencies block in
android/app/build.gradle
:compile project(':react-native-app-auth')
To setup the iOS project, you need to perform three steps:
This library depends on the native AppAuth-ios project. To keep the React Native library agnostic of your dependency management method, the native libraries are not distributed as part of the bridge.
AppAuth supports three options for dependency management.
-
CocoaPods
With CocoaPods, add the following line to your
Podfile
:pod 'AppAuth', '>= 0.94'
Then run
pod install
. Note that version 0.94 is the first of the library to support iOS 11. -
Carthage
With Carthage, add the following line to your
Cartfile
:github "openid/AppAuth-iOS" "master"
Then run
carthage bootstrap
. -
Static Library
You can also use AppAuth-iOS as a static library. This requires linking the library and your project and including the headers. Suggested configuration:
- Create an XCode Workspace.
- Add
AppAuth.xcodeproj
to your Workspace. - Include libAppAuth as a linked library for your target (in the "General -> Linked Framework and Libraries" section of your target).
- Add
AppAuth-iOS/Source
to your search paths of your target ("Build Settings -> "Header Search Paths").
If you intend to support iOS 10 and older, you need to define the supported redirect URL schemes in
your Info.plist
as follows:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>com.your.app.identifier</string>
<key>CFBundleURLSchemes</key>
<array>
<string>io.identityserver.demo</string>
</array>
</dict>
</array>
CFBundleURLName
is any globally unique string. A common practice is to use your app identifier.CFBundleURLSchemes
is an array of URL schemes your app needs to handle. The scheme is the beginning of your OAuth Redirect URL, up to the scheme separator (:
) character.
You need to retain the auth session, in order to continue the authorization flow from the redirect. Follow these steps:
RNAppAuth
will call on the given app's delegate via [UIApplication sharedApplication].delegate
.
Furthermore, RNAppAuth
expects the delegate instance to conform to the protocol RNAppAuthAuthorizationFlowManager
.
Make AppDelegate
conform to RNAppAuthAuthorizationFlowManager
with the following changes to AppDelegate.h
:
+ #import "RNAppAuthAuthorizationFlowManager.h"
- @interface AppDelegate : UIResponder <UIApplicationDelegate>
+ @interface AppDelegate : UIResponder <UIApplicationDelegate, RNAppAuthAuthorizationFlowManager>
+ @property(nonatomic, weak)id<RNAppAuthAuthorizationFlowManagerDelegate>authorizationFlowManagerDelegate;
The authorization response URL is returned to the app via the iOS openURL app delegate method, so
you need to pipe this through to the current authorization session (created in the previous
instruction). Thus, implement the following method from UIApplicationDelegate
in AppDelegate.m
:
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *, id> *)options {
return [self.authorizationFlowManagerDelegate resumeExternalUserAgentFlowWithURL:url];
}
The approach mentioned above should also be possible to employ with Swift. In this case one should have to import RNAppAuth
and make AppDelegate
conform to RNAppAuthAuthorizationFlowManager
. Note that this has not been tested.
AppDelegate.swift
should look something like this:
@import RNAppAuth
class AppDelegate: UIApplicationDelegate, RNAppAuthAuthorizationFlowManager {
public weak var authorizationFlowManagerDelegate: RNAppAuthAuthorizationFlowManagerDelegate?
func application(
_ app: UIApplication,
open url: URL,
options: [UIApplicationOpenURLOptionsKey: Any] = [:]) -> Bool {
return authorizationFlowManagerDelegate?.resumeExternalUserAgentFlowWithURL(with: url) ?? false
}
}
To setup the Android project, you need to perform two steps:
This library depends on the AppAuth-Android project. The native dependencies for Android are automatically installed by Gradle, but you need to add the correct Android Support library version to your project:
- Add the Google Maven repository in your
android/build.gradle
repositories { google() }
- Make sure the appcompat version in
android/app/build.gradle
matches the one expected by AppAuth. If you generated your project usingreact-native init
, you may have an older version of the appcompat libraries and need to upgdrade:dependencies { compile "com.android.support:appcompat-v7:25.3.1" }
- If necessary, update the
compileSdkVersion
to 25:android { compileSdkVersion 25 }
To
capture the authorization redirect,
add the following property to the defaultConfig in android/app/build.gradle
:
android {
defaultConfig {
manifestPlaceholders = [
appAuthRedirectScheme: 'io.identityserver.demo'
]
}
}
The scheme is the beginning of your OAuth Redirect URL, up to the scheme separator (:
) character.
import { authorize } from 'react-native-app-auth';
// base config
const config = {
issuer: '<YOUR_ISSUER_URL>',
clientId: '<YOUR_CLIENT_ID>',
redirectUrl: '<YOUR_REDIRECT_URL>',
scopes: ['<YOUR_SCOPES_ARRAY>'],
};
// use the client to make the auth request and receive the authState
try {
const result = await authorize(config);
// result includes accessToken, accessTokenExpirationDate and refreshToken
} catch (error) {
console.log(error);
}
See example configurations for different providers below.
Some authentication providers, including examples cited below, require you to provide a client secret. The authors of the AppAuth library
strongly recommend you avoid using static client secrets in your native applications whenever possible. Client secrets derived via a dynamic client registration are safe to use, but static client secrets can be easily extracted from your apps and allow others to impersonate your app and steal user data. If client secrets must be used by the OAuth2 provider you are integrating with, we strongly recommend performing the code exchange step on your backend, where the client secret can be kept hidden.
Having said this, in some cases using client secrets is unavoidable. In these cases, a clientSecret
parameter can be provided to authorize
/refresh
calls when performing a token request.
This library supports authenticating for Identity Server 4 out of the box. Some quirks:
- In order to enable refresh tokens,
offline_access
must be passed in as a scope variable - In order to revoke the access token, we must sent client id in the method body of the request. This is not part of the OAuth spec.
// Note "offline_access" scope is required to get a refresh token
const config = {
issuer: 'https://demo.identityserver.io',
clientId: 'native.code',
redirectUrl: 'io.identityserver.demo:/oauthredirect',
scopes: ['openid', 'profile', 'offline_access']
};
// Log in to get an authentication token
const authState = await authorize(config);
// Refresh token
const refreshedState = await refresh({
...config,
refreshToken: authState.refreshToken,
});
// Revoke token, note that Identity Server expects a client id on revoke
await revoke(config, {
tokenToRevoke: refreshedState.refreshToken,
sendClientId: true
});
Example server configuration
var client = new Client
{
ClientId = "native.code",
ClientName = "Native Client (Code with PKCE)",
RequireClientSecret = false,
RedirectUris = { "io.identityserver.demo:/oauthredirect" },
AllowedGrantTypes = GrantTypes.Code,
RequirePkce = true,
AllowedScopes = { "openid", "profile" },
AllowOfflineAccess = true
};
This library supports authenticating with Identity Server 3. The only difference from
Identity Server 4 is that it requires a clientSecret
and there is no way to opt out of it.
// You must include a clientSecret
const config = {
issuer: 'your-identityserver-url',
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
redirectUrl: 'com.your.app.name:/oauthredirect',
scopes: ['openid', 'profile', 'offline_access']
};
// Log in to get an authentication token
const authState = await authorize(config);
// Refresh token
const refreshedState = await refresh({
...config,
refreshToken: authState.refreshToken,
});
// Revoke token, note that Identity Server expects a client id on revoke
await revoke(config, {
tokenToRevoke: refreshedState.refreshToken,
sendClientId: true
});
Example server configuration
var client = new Client
{
ClientId = "native.code",
ClientName = "Native Client (Code with PKCE)",
Flow = Flows.AuthorizationCodeWithProofKey,
RedirectUris = { "com.your.app.name:/oauthredirect" },
ClientSecrets = new List<Secret> { new Secret("your-client-secret".Sha256()) },
AllowAccessToAllScopes = true
};
Full support out of the box.
const config = {
issuer: 'https://accounts.google.com',
clientId: 'GOOGLE_OAUTH_APP_GUID.apps.googleusercontent.com',
redirectUrl: 'com.googleusercontent.apps.GOOGLE_OAUTH_APP_GUID:/oauth2redirect/google',
scopes: ['openid', 'profile', 'offline_access']
};
// Log in to get an authentication token
const authState = await authorize(config);
// Refresh token
const refreshedState = await refresh(config, {
refreshToken: authState.refreshToken
});
// Revoke token
await revoke(config, {
tokenToRevoke: refreshedState.refreshToken
});
Full support out of the box.
If you're using Okta and want to add App Auth to your React Native application, you'll need an application to authorize against. If you don't have an Okta Developer account, you can signup for free.
Log in to your Okta Developer account and navigate to Applications > Add Application. Click Native and click the Next button. Give the app a name youโll remember (e.g.,
React Native
), selectRefresh Token
as a grant type, in addition to the defaultAuthorization Code
. Copy the Login redirect URI (e.g.,com.oktapreview.dev-158606:/callback
) and save it somewhere. You'll need this value when configuring your app.Click Done and you'll see a client ID on the next screen. Copy the redirect URI and clientId values into your App Auth config.
const config = {
issuer: 'https://{yourOktaDomain}.com/oauth2/default',
clientId: '{clientId}',
redirectUrl: 'com.{yourReversedOktaDomain}:/callback',
scopes: ['openid', 'profile']
};
// Log in to get an authentication token
const authState = await authorize(config);
// Refresh token
const refreshedState = await refresh(config, {
refreshToken: authState.refreshToken,
});
// Revoke token
await revoke(config, {
tokenToRevoke: refreshedState.refreshToken
});
Keycloak does not specify a revocation endpoint so revoke functionality doesn't work.
If you use JHipster's default Keycloak Docker image, everything will work with the following settings, except for revoke.
const config = {
issuer: 'http://localhost:9080/auth/realms/jhipster',
clientId: 'web_app',
redirectUrl: '<YOUR_REDIRECT_SCHEME>:/callback'
scopes: ['openid', 'profile']
};
// Log in to get an authentication token
const authState = await authorize(config);
// Refresh token
const refreshedState = await refresh(config, {
refreshToken: authState.refreshToken,
});
Azure Active Directory does not specify a revocation endpoint because the access token are not revokable. Therefore revoke
functionality doesn't work.
See the Azure docs on requesting an access token for more info on additional parameters.
Please Note:
- The Azure docs recommend
'urn:ietf:wg:oauth:2.0:oob'
as theredirectUrl
. Scopes
is ignored.additionalParameters.resource
may be required based on the tenant settings.
const config = {
issuer: 'https://login.microsoftonline.com/your-tenant-id',
clientId: 'your-client-id',
redirectUrl: 'urn:ietf:wg:oauth:2.0:oob',
scopes: [], // ignored by Azure AD
additionalParameters: {
resource: 'your-resource'
}
};
// Log in to get an authentication token
const authState = await authorize(config);
// Refresh token
const refreshedState = await refresh(config, {
refreshToken: authState.refreshToken,
});
Uber provides an OAuth 2.0 endpoint for logging in with a Uber user's credentials. You'll need to first create an Uber OAuth application here.
Please note:
- Uber does not provide a OIDC discovery endpoint, so
serviceConfiguration
is used instead. - Uber OAuth requires a client secret.
const config = {
clientId: 'your-client-id-generated-by-uber',
clientSecret: 'your-client-secret-generated-by-uber',
redirectUrl: 'com.whatever.url.you.configured.in.uber.oauth://redirect', //note: path is required
scopes: ['profile', 'delivery'], // whatever scopes you configured in Uber OAuth portal
serviceConfiguration: {
authorizationEndpoint: 'https://login.uber.com/oauth/v2/authorize',
tokenEndpoint: 'https://login.uber.com/oauth/v2/token',
revocationEndpoint: 'https://login.uber.com/oauth/v2/revoke'
}
};
// Log in to get an authentication token
const authState = await authorize(config);
// Refresh token
const refreshedState = await refresh(config, {
refreshToken: authState.refreshToken,
});
// Revoke token
await revoke(config, {
tokenToRevoke: refreshedState.refreshToken
});
Fitbit provides an OAuth 2.0 endpoint for logging in with a Fitbit user's credentials. You'll need to first register your Fitbit application here.
Please note:
- Fitbit does not provide a OIDC discovery endpoint, so
serviceConfiguration
is used instead. - Fitbit OAuth requires a client secret.
const config = {
clientId: 'your-client-id-generated-by-uber',
clientSecret: 'your-client-secret-generated-by-fitbit',
redirectUrl: 'com.whatever.url.you.configured.in.uber.oauth://redirect', //note: path is required
scopes: ['activity', 'sleep'],
serviceConfiguration: {
authorizationEndpoint: 'https://www.fitbit.com/oauth2/authorize',
tokenEndpoint: 'https://api.fitbit.com/oauth2/token',
revocationEndpoint: 'https://api.fitbit.com/oauth2/revoke'
}
};
// Log in to get an authentication token
const authState = await authorize(config);
// Refresh token
const refreshedState = await refresh(config, {
refreshToken: authState.refreshToken,
});
// Revoke token
await revoke(config, {
tokenToRevoke: refreshedState.refreshToken
});
Thanks goes to these wonderful people (emoji key):
Kadi Kraman ๐ป ๐ ๐ |
Jani Evรคkallio ๐ก ๐ |
Phil Plรผckthun ๐ ๐ ๐ค |
Imran Sulemanji ๐ค ๐ |
JP ๐ค ๐ |
Matt Cubitt ๐ค ๐ |
---|
This project follows the all-contributors specification. Contributions of any kind are welcome!