
Research
Security News
The Growing Risk of Malicious Browser Extensions
Socket researchers uncover how browser extensions in trusted stores are used to hijack sessions, redirect traffic, and manipulate user behavior.
react-native-app-auth
Advanced tools
React Native bridge for AppAuth for supporting any OAuth 2 provider
The react-native-app-auth package is a React Native bridge for the AppAuth-iOS and AppAuth-Android SDKs for communicating with OAuth 2.0 and OpenID Connect providers. It allows developers to authenticate users and obtain access tokens for accessing protected resources.
Authorization Code Flow
This feature allows you to perform the Authorization Code Flow, which is a common OAuth 2.0 flow for obtaining access tokens. The code sample demonstrates how to configure the authorization request and handle the response.
{
"import": "import { authorize } from 'react-native-app-auth';",
"config": "const config = {\n issuer: 'https://accounts.google.com',\n clientId: 'YOUR_CLIENT_ID',\n redirectUrl: 'com.yourapp:/oauth2redirect',\n scopes: ['openid', 'profile']\n};",
"authorize": "authorize(config).then(result => console.log(result)).catch(error => console.error(error));"
}
Token Refresh
This feature allows you to refresh an access token using a refresh token. The code sample shows how to use the refresh function to obtain a new access token.
{
"import": "import { refresh } from 'react-native-app-auth';",
"refreshToken": "refresh(config, { refreshToken: 'YOUR_REFRESH_TOKEN' }).then(result => console.log(result)).catch(error => console.error(error));"
}
Revoke Token
This feature allows you to revoke an access or refresh token. The code sample demonstrates how to revoke a token using the revoke function.
{
"import": "import { revoke } from 'react-native-app-auth';",
"revokeToken": "revoke(config, { tokenToRevoke: 'YOUR_ACCESS_TOKEN', sendClientId: true }).then(() => console.log('Token revoked')).catch(error => console.error(error));"
}
react-native-oauth is another package for handling OAuth authentication in React Native apps. It supports multiple OAuth providers and offers a simpler API for common authentication tasks. However, it may not be as actively maintained or as feature-rich as react-native-app-auth, which is specifically designed to work with the AppAuth SDKs.
react-native-firebase provides a comprehensive suite of tools for integrating Firebase services into React Native apps, including authentication. While it offers OAuth support through Firebase Authentication, it is more focused on Firebase's ecosystem and may not provide the same level of customization for OAuth flows as react-native-app-auth.
React Native bridge for AppAuth-iOS and AppAuth-Android - an SDK for communicating with OAuth2 providers. It also supports the PKCE extension to OAuth.
This library should support any OAuth provider that implements the OAuth2 spec but it has only been tested with:
The library uses auto-discovery which mean it relies on the the .well-known/openid-configuration endpoint to discover all auth endpoints automatically. It will be possible to extend the library later to add custom configuration.
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 AppAuth from 'react-native-app-auth';
const appAuth = new AppAuth(config);
const result = await appAuth.authorize(scopes);
// returns accessToken, accessTokenExpirationDate and refreshToken
This method will refresh the accessToken using the refreshToken. Some auth providers will also give you a new refreshToken
const result = await appAuth.refresh(refreshToken, scopes);
// returns accessToken, accessTokenExpirationDate and (maybe) refreshToken
This method will revoke a token. The tokenToRevoke can be either an accessToken or a refreshToken
// note, sendClientId=true will only be required when using IdentityServer
const result = await appAuth.revokeToken(tokenToRevoke, sendClientId);
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.
Libraries
β Add Files to [your project's name]
node_modules
β react-native-app-auth
and add RNAppAuth.xcodeproj
libRNAppAuth.a
to your project's Build Phases
β Link Binary With Libraries
Cmd+R
)<android/app/src/main/java/[...]/MainActivity.java
import com.reactlibrary.RNAppAuthPackage;
to the imports at the top of the filenew RNAppAuthPackage()
to the list returned by the getPackages()
methodandroid/settings.gradle
:
include ':react-native-app-auth'
project(':react-native-app-auth').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-app-auth/android')
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.
With CocoaPods,
add the following line to your Podfile
:
pod 'AppAuth'
Then run pod install
.
With Carthage, add the following
line to your Cartfile
:
github "openid/AppAuth-iOS" "master"
Then run carthage bootstrap
.
You can also use AppAuth-iOS as a static library. This requires linking the library and your project and including the headers. Suggested configuration:
AppAuth.xcodeproj
to your Workspace.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 have a property in your AppDelegate to hold the auth session, in order to continue the authorization flow from the redirect. To add this, open AppDelegate.h
in your project and add the following lines:
+ @protocol OIDAuthorizationFlowSession;
@interface AppDelegate : UIResponder <UIApplicationDelegate>
+ @property(nonatomic, strong, nullable) id<OIDAuthorizationFlowSession> currentAuthorizationFlow;
@property (nonatomic, strong) UIWindow *window;
@end
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). To do this, open AppDelegate.m
and add an import statement:
#import "AppAuth.h"
And in the bottom of the class, add the following handler:
- (BOOL)application:(UIApplication *)app
openURL:(NSURL *)url
options:(NSDictionary<NSString *, id> *)options {
if ([_currentAuthorizationFlow resumeAuthorizationFlowWithURL:url]) {
_currentAuthorizationFlow = nil;
return YES;
}
return NO;
}
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:
android/build.gradle
repositories {
google()
}
android/app/build.gradle
matches the one expected by AppAuth. If you generated your project using react-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"
}
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 AppAuth from 'react-native-app-auth';
// initialise the client with your configuration
const appAuth = new AppAuth({
issuer: '<YOUR_ISSUER_URL>',
clientId: '<YOUR_CLIENT_ID',
redirectUrl: '<YOUR_REDIRECT_URL>',
});
// use the client to make the auth request and receive the authState
try {
const scopes = ['profile'];
const result = await appAuth.authorize(scopes);
// result includes accessToken, accessTokenExpirationDate and refreshToken
} catch (error) {
console.log(error);
}
See example configurations for different providers below.
This library supports authenticating for Identity Server 4 out of the box. Some quirks:
offline_access
must be passed in as a scope variable// Note "offline_access" scope is required to get a refresh token
const scopes = ["openid", "profile", "offline_access"];
const appAuth = new AppAuth({
issuer: "https://demo.identityserver.io",
clientId: "native.code",
redirectUrl: "io.identityserver.demo:/oauthredirect"
});
// Log in to get an authentication token
const authState = await appAuth.authorize(scopes);
// Refresh token
const refreshedState = appAuth.refresh(authState.refreshToken, scopes);
// Revoke token, note that Identity Server expects a client id on revoke
const sendClientIdOnRevoke = true;
await appAuth.revokeToken(refreshedState.refreshToken, sendClientIdOnRevoke);
Full support out of the box.
const scopes = ["openid", "profile"];
const appAuth = new AppAuth({
issuer: "https://accounts.google.com",
clientId: "GOOGLE_OAUTH_APP_GUID.apps.googleusercontent.com",
redirectUrl: "com.googleusercontent.apps.GOOGLE_OAUTH_APP_GUID:/oauth2redirect/google"
});
// Log in to get an authentication token
const authState = await appAuth.authorize(scopes);
// Refresh token
const refreshedState = appAuth.refresh(authState.refreshToken, scopes);
// Revoke token
await appAuth.revokeToken(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!
FAQs
React Native bridge for AppAuth for supporting any OAuth 2 provider
The npm package react-native-app-auth receives a total of 142,670 weekly downloads. As such, react-native-app-auth popularity was classified as popular.
We found that react-native-app-auth demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.Β It has 17 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover how browser extensions in trusted stores are used to hijack sessions, redirect traffic, and manipulate user behavior.
Research
Security News
An in-depth analysis of credential stealers, crypto drainers, cryptojackers, and clipboard hijackers abusing open source package registries to compromise Web3 development environments.
Security News
pnpm 10.12.1 introduces a global virtual store for faster installs and new options for managing dependencies with version catalogs.