- Notifications
You must be signed in to change notification settings - Fork211
A react-native wrapper for social authentication login for both Android and iOS
License
fullstackreact/react-native-oauth
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Thereact-native-oauth library provides an interface to OAuth 1.0 and OAuth 2.0 providers with support for the following providers for React Native apps:
- Github
- Slack
This library cuts out the muck of dealing with theOAuth 1.0 andOAuth 2.0 protocols in react-native apps. The API is incredibly simple and straight-forward and is intended on getting you up and running quickly with OAuth providers (such as Facebook, Github, Twitter, etc).
importOAuthManagerfrom'react-native-oauth';constmanager=newOAuthManager('firestackexample')manager.configure({twitter:{consumer_key:'SOME_CONSUMER_KEY',consumer_secret:'SOME_CONSUMER_SECRET'},google:{callback_url:`io.fullstack.FirestackExample:/oauth2redirect`,client_id:'YOUR_CLIENT_ID',client_secret:'YOUR_SECRET'}});// ...manager.authorize('google',{scopes:'profile email'}).then(resp=>console.log('Your users ID')).catch(err=>console.log('There was an error'));
Due to other time contraints, I cannot continue to work on react-native-oauth for the time it deserves. If you're interested in supporting this library, please help! It's a widely used library and I'd love to continue supporting it. Looking for maintainers!
- Isolates the OAuth experience to a few simple methods.
- Atomatically stores the tokens for later retrieval
- Works with many providers and simple to add new providers
- Works on both Android and iOS
- Makes calling API methods a snap
- Integrates seamlessly with Firestack (but can be used without it)
Installreact-native-oauth in the usual manner usingnpm:
npminstall--savereact-native-oauth
As we are integrating with react-native, we have a little more setup to integrating with our apps.
Important: This willnot work if you do not complete all the steps:
- Link the
RCTLinkingManagerproject - Update your
AppDelegate.hfile - Add KeychainSharing in your app
- Link the
react-native-oauthproject with your application (react-native link) - Register a URL type of your application (Info tab -- see below)
Sincereact-native-oauth depends upon theRCTLinkingManager (from react-native core), we'll need to make sure we link this in our app.
In your app, add the following line to yourHEADER SEARCH PATHS:
$(SRCROOT)/../node_modules/react-native-oauth/ios/OAuthManager$(SRCROOT)/../node_modules/react-native/Libraries/LinkingIOSNext, navigate to the neighboring "Build Phases" section of project settings, find the "Link Binary with Library" drop down, expand it, and click the "+" to addlibOAuthManager.a to the list.
Make sure to Update yourAppDelegate.m as below, otherwise it willnot work.
Automatically withrnpm
To automatically link ourreact-native-oauth client to our application, use thernpm tool.rnpm is a React Native package manager which can help to automate the process of linking package environments.
react-native link react-native-oauth
Note: due to some restrictions on iOS, this module requires you to install cocoapods. The process has been semi-automated through using the abovereact-native link command.
Once you have linked this library, run the following command in the root directory:
(cd ios && pod install)Open in xcode the created.xcworkspace in theios/ directory (NOT THE.xproj file) when it's complete.
When working on iOS 10, we'll need to enableKeychain Sharing Entitlement inCapabilities of the build target ofio.fullstack.oauth.AUTH_MANAGER.
Required step
We'll need to handle app loading from a url with our app in order to handle authentication from other providers. That is, we'll need to make sure our app knows about the credentials we're authenticating our users against when the app loadsafter a provider is authenticated against.
We need to add a callback method in ourios/AppDelegate.m file and then call our OAuthManager helper method. Let's load theios/AppDelegate.m file and add the following all the way at the bottom (but before the@end):
// Add the import at the top:#import"OAuthManager.h"// ...@implementationAppDelegate// ...- (BOOL)application:(UIApplication *)applicationopenURL:(NSURL *)urlsourceApplication:(NSString *)sourceApplicationannotation:(id)annotation {return [OAuthManagerhandleOpenUrl:applicationopenURL:urlsourceApplication:sourceApplicationannotation:annotation];}
In addition, we'll need to set up the handlers within the iOS app. Add the following line somewhere in yourapplication:didFinishLaunchingWithOptions: method, like so:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{NSURL *jsCodeLocation; jsCodeLocation = [[RCTBundleURLProvidersharedSettings]jsBundleURLForBundleRoot:@"index.ios"fallbackResource:nil];// other existing setup here// ADD THIS LINE SOMEWHERE IN THIS FUNCTION [OAuthManagersetupOAuthHandler:application];// ... [self.windowmakeKeyAndVisible];returnYES;}
When our app loads up with a request that is coming back from OAuthManagerand matches the url pattern, OAuthManager will take over and handle the rest and storing the credentials for later use.
In order for our app to load through these callbacks, we need to tell our iOS app that we want to load them. In order to do that, we'll have to create some URL schemes to register our app. Some providers require specific schemes (mentioned later).
These URL schemes can be added by navigating to to theinfo panel of our app in Xcode (see screenshot).
Let's add the appropriate one for our provider. For instance, to set up twitter, add the app name as a URL scheme in the URL scheme box.
After we linkreact-native-oauth to our application, we're ready to go. Android integration is much simpler, thanks to the in-app browser ability for our apps.react-native-oauth handles this for you.
One note,all of the callback urls follow the scheme:http://localhost/[provider_name]. Make sure this is set as a configuration for each provider below (documented in the provider setup sections).
Make sure you add the following to yourandroid/build.gradle file:
maven { url "https://jitpack.io" }For instance, an exampleandroid/build.gradle file would look like this:
// Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript { // ...}allprojects { repositories { mavenLocal() jcenter() maven { url "https://jitpack.io" } // <~ ADD THIS LINE maven { url "$rootDir/../node_modules/react-native/android" } }}In our JS, we can create the manager by instantiating a new instance of it using thenew method and passing it the name of our app:
constmanager=newOAuthManager('firestackexample')
We need to pass the name of our app as the oauth manager uses this to create callback keys. Thismust match the URL route created in your iOS app. For instance, above we created a URL scheme for Twitter. Pass this as the string in theOAuthManager constructor.
Providers, such as Facebook require some custom setup for each one. The following providers have been implemented and we're working on making more (and making it easier to add more, although the code is not impressively complex either, so it should be relatively simple to add more providers).
In order to configure providers, thereact-native-oauth library exports theconfigureProvider() method, which acceptstwo parameters and returns a promise:
- The provider name, such as
twitterandfacebook - The provider's individual credentials
For instance, this might look like:
constconfig={twitter:{consumer_key:'SOME_CONSUMER_KEY',consumer_secret:'SOME_CONSUMER_SECRET'},facebook:{client_id:'YOUR_CLIENT_ID',client_secret:'YOUR_CLIENT_SECRET'}}// Create the managerconstmanager=newOAuthManager('firestackexample')// configure the managermanager.configure(config);
Theconsumer_key andconsumer_secret values aregenerally provided by the provider development program. In the case oftwitter, we can create an app and generate these values through theirdevelopment dashboard.
The following list are the providers we've implemented thus far inreact-native-oauth and therequired keys to pass when configuring the provider:
To authenticate against twitter, we need to register a Twitter application. Register your twitter application (or create a new one atapps.twitter.com).
Once you have created one, navigate to the application and find theKeys and Access Tokens. Take note of the consumer key and secret:
For the authentication to work properly, you need to set the Callback URL. It doesn't matter what you choose as long as its a valid url.
Twitter's URL scheme needs to be the app name (that we pass into the constructor method). Make sure we have one registered in Xcode as the same name:
Add these values to the authorization configuration to pass to theconfigure() method as:
constconfig={twitter:{consumer_key:'SOME_CONSUMER_KEY',consumer_secret:'SOME_CONSUMER_SECRET'}}
To add facebook authentication, we'll need to have a Facebook app. To create one (or use an existing one), navigate todevelopers.facebook.com/.
Find or create an application and find the app id. Take note of this app id. Next, navigate to theSettings panel and find your client_secret.
Before we leave the Facebook settings, we need to tell Facebook we have a new redirect url to register. Navigate to the bottom of the page and add the following into thebundle ID field:
fb{YOUR_APP_ID}
For instance, my app ID in this example is:1745641015707619. In theBundle ID field, I have addedfb1745641015707619.
For Android, you will also need to set the redirect url tohttp://localhost/facebook in the Facebook Login settings.
We'll need to create a new URL scheme for Facebook and (this is a weird bug on the Facebook side) the facebook redirect URL schememust be the first one in the list. The URL scheme needs to be the same id as theBundle ID copied from above:
Back in our application, add the App ID and the secret as:
constconfig={facebook:{client_id:'YOUR_APP_ID',client_secret:'YOUR_APP_SECRET'}}
To add Google auth to our application, first we'll need to create a google application. Create or use an existing one by heading to thedevelopers.google.com/ page (or the console directly athttps://console.developers.google.com).
We need to enable theIdentity Toolkit API API. Click onEnable API and add this api to your app. Once it's enabled, we'll need to collect our credentials.
Navigate to theCredentials tab and create a new credential. Create aniOS API credential. Take note of theclient_id and theiOS URL scheme. In addition, make sure to set the bundle ID as the bundle id in our application in Xcode:
Take note of theiOS URL Scheme. We'll need to add this as a URL scheme in our app. In theInfo panel of our app target (in Xcode), add the URL scheme:
Finally, add theclient_id credential as the id from the url page as well as the ios scheme (with any path) in our app configuration:
constconfig={google:{callback_url:`[IOS SCHEME]:/google`,client_id:'YOUR_CLIENT_ID'}}
To set up Google on Android, follow the same steps as before, except this time instead of creating an iOS API, create aweb api credential. Make sure to add theredirect url at the bottom (it defaults tohttp://localhost/google):
When creating an Android-specific configuration, create a file calledconfig/development.android.js. React Native will load it instead of theconfig/development.js file automatically on Android.
Adding Github auth to our application is pretty simple as well. We'll need to create a web application on the github apps page, which can be found athttps://github.com/settings/developers. Create one, making sure to addtwo apps (one for iOS and one for Android) with the callback urls as:
- ios: [app_name]:// oauth (for example:
firestackexample://oauth) - android:http://localhost/github
Take note of theclient_id andclient_secret
TheiOS URL Scheme is the same as the twitter version, which means we'll just add the app name as a URL scheme (i.e.firestackexample).
Add theclient_id andclient_secret credentials to your configuration object:
constconfig={github:{client_id:'YOUR_CLIENT_ID',client_secret:'YOUR_CLIENT_SECRET'}}
We'll need to create an app first. Head to the slack developer docs athttps://slack.com/developers.
Click on the Getting Started button:
From here, find thecreate an app link:
Take note of theclient_id and theclient_secret. We'll place these in our configuration object just like so:
constconfig={slack:{client_id:'YOUR_CLIENT_ID',client_secret:'YOUR_CLIENT_SECRET'}}
Lastly, Slack requires us to add a redirect_url.
ForiOS: the callback_url pattern is${app_name}://oauth, so make sure to add your redirect_url where it asks for them before starting to work with the API.
forAndroid: thecallback_url pattern ishttp://localhost/slack. Be sure to add this to your list of redirect urls.
We can use the manager in our app using theauthorize() method on the manager.
Theauthorize method takes two arguments (the first one is required):
- The provider we wish to authenticate against (i.e. twitter, facebook)
- The list of options on a per-provider basis (optional)
For example:
manager.authorize('twitter').then(resp=>console.log(resp)).catch(err=>console.log(err));
This method returns a promise that is resolved once the authentication has been completed. You'll get access to the authentication keys in theresp object.
Theresp object is set as follows:
{status:"ok",response:{authorized:true,(boolean)uuid:"UUID",(userUUID)credentials:{access_token:"access token",refresh_token:"refresh token",type:1}}}
The second argument accepts an object where we can ask for additional scopes, override default values, etc.
manager.authorize('google',{scopes:'email,profile'}).then(resp=>console.log(resp)).catch(err=>console.log(err));
- Scopes are a list of scopescomma separated as a string.
We can use OAuthManager to make requests to endpoints from our providers as well. For instance, let's say we want to get a user's time line from twitter. We would make the request to the urlhttps://api.twitter.com/1.1/statuses/user_timeline.json
If our user has been authorized for thi request, we can execute the request using the credentials stored by the OAuthManager.
ThemakeRequest() method accepts 3 parameters:
- The provider we're making a request to
- The url (or path) we want to make the request
- Any additional options
We can pass a list of options for our request with the last argument. The keys OAuthManager recognizes are:
params- The query parametersmethod- The http method to make the request with.
Available HTTP methods:
- get
- post
- put
- delete
- head
- options
- trace
constuserTimelineUrl='https://api.twitter.com/1.1/statuses/user_timeline.json';manager.makeRequest('twitter',userTimelineUrl).then(resp=>{console.log('Data ->',resp.data);});
"me" represents the authenticated user, in any call to the Google+ API
constgoogleUrl='https://www.googleapis.com/plus/v1/people/me';manager.makeRequest('google',googleUrl).then(resp=>{console.log('Data -> ',resp.data);});
It's possible to use just the path as well. For instance, making a request with Facebook at the/me endpoint can be:
manager.makeRequest('facebook','/me').then(resp=>{console.log('Data ->',resp.data);});
To add more data to our requests, we can pass a third argument:
manager.makeRequest('facebook','/me',{headers:{'Content-Type':'application/java'},params:{email:'me+rocks@ari.io'}}).then(resp=>{console.log('Data ->',resp.data);});
Since OAuthManager handles storing user accounts, we can query it to see which accounts have already been authorized or not usingsavedAccounts():
manager.savedAccounts().then(resp=>{console.log('account list: ',resp.accounts);})
We candeauthorize() our user's from using the provider by calling thedeauthorize() method. It accepts a single parameter:
- The
providerwe want to remove from our user credentials.
manager.deauthorize('twitter');
To add your own providers you can use theaddProvider() method and fill in your provider details:
manager.addProvider({'name_of_provider':{auth_version:'2.0',authorize_url:'https://provider.dev/oauth',access_token_url:'https://provider.dev/oauth/token',callback_url:({app_name})=>`${app_name}://oauth`,}});
This isopen-source software and we can make it rock for everyone through contributions.
git clone https://github.com/fullstackreact/react-native-oauth.gitcd react-native-oauthnpm install- Simplify method of adding providers
- Add github(https://developer.github.com/v3/oauth/) support
- Add Google support
- Add Facebook support
- Add Android support
About
A react-native wrapper for social authentication login for both Android and iOS
Resources
License
Uh oh!
There was an error while loading.Please reload this page.




















