Back to Blog Home
← all posts

Introducing the NativeScript OAuth Plugin

August 29, 2016 — by Alexander Ziskind

nativescript-oauth-logo

OAuth has been adopted by many organizations, large and small, as the (current) best standard for authenticating and authorizing their users. OAuth 2.0 being the latest iteration of the standard and it's used to offload the burdensome security related parts of applications to third party experts.

While writing your own OAuth flow for your apps could be a fun experience (for those of you that really enjoy headaches), most of the time we are happy plugging in a third party SDK so we can authenticate against their service.

In the NativeScript world, we could use third party SDKs which would require you to integrate them yourself, or we could simply use the new OAuth plugin available on NPM called nativescript-oauth. The plugin is now out of beta and supports both iOS and Android. Here's how you can start.

Versions used in this post
  • NativeScript: 2.2.1
  • nativescript-oauth plugin: 1.0.2
Note: If you're new to this plugin, then plug away. However, if you've previously installed the beta, please take a look at the changes described in this post


OAuth what?

Here's the crux. Many APIs are secured by access tokens and the OAuth dance between servers is meant to produce one of these tokens that your app can send to the API you're working with along with the regular calls you're making. To get the access token, your user needs to login at the third party authentication website.

NativeScript_OAuth_01


Why would I want this plugin?

  1. Doesn't use any third party libraries. All code is written in JavaScript
  2. Open source, of course. We've already taken community contribution, which is awesome
  3. All the inner workings of OAuth are abstracted away so you don't need to worry about it
  4. Integrates seamlessly with the upcoming Microsoft Graph TypeScript SDK that we've diligently working on
  5. Plugin was built with TypeScript so it provides TypeScript support out of the box - no extra definitions needed


Prerequisites

You'll have to do a little preparation before your app will work with a third party authentication provider, since you're relying on them to do the work for you. This will require you to register your app with the third party such as Microsoft or Facebook. Then you're off to the races. And if you already have the app registered, then great!

You want to decide what third party OAuth 2.0 provider you want to use for your users to login. If you're writing an app that uses the Facebook API, then you're going to need an access token provided by Facebook's authentication servers. If you're writing an app that uses the Microsoft Graph or Office 365, you'll need an access token from Microsoft.
Then you need to register your app with the third party provider.

If you want to watch a video tutorial on setting up the app with a Microsoft account, you can view it here.

Setup Instructions

Once you've created your NativeScript project and have your app registered with your OAuth provider, you can install the NativeScript OAuth plugin, which is just a NPM package that is easily installed using this command

tns plugin add nativescript-oauth

Wherever you need to use the nativescript-oauth module, you need to import it

import * as tnsOAuthModule from 'nativescript-oauth';


Office365/Microsoft Graph

Instructions on registering a Microsoft Live app or Office 365 app or Microsoft Graph app are here

In your app.ts file (or app.js if you're not using TypeScript), you will bootstrap your Microsoft authentication provider data bits like this

var o365InitOptions : tnsOAuthModule.TnsOAuthOptionsOffice365 = {
    clientId: 'e392f6aa-da5c-434d-a42d-a0e0a27d3964', //client id for application (GUID)
    scope: ['Files.ReadWrite', 'offline_access']
};
tnsOAuthModule.initOffice365(o365InitOptions);

Note: Make sure you do this before you execute application.start(…)

Facebook

Instructions on setting up your app with Facebook are here.

Again in your app.ts file you will bootstrap your Facebook authentication provider like this

var facebookInitOptions : tnsOAuthModule.TnsOAuthOptionsFacebook = {
    clientId: '1819818654921817',
    clientSecret: 'b7e58f212b51e4d639bed857171c992a',
    scope: ['email']
};
tnsOAuthModule.initFacebook(facebookInitOptions);

Note: Again, be sure you do this before application.start(…)

Notice that Microsoft only requires the ClientId and scope, but Facebook also require the ClientSecret. These are all values you should have access to when registering your app. ClientId is the identifier of your application and is some unique value. Microsoft uses UUIDs and Facebook uses long integers. Scope tells the provider what permissions your app has. I’m sure you’ve seen the screens that say something like “App so-and-so want to post to Facebook on your behalf”; well that’s the permission level that you control with scope. Read the provider’s documentation to get all the available scopes.



Logging In

Once you have that done, you can call the login function whenever you need to authenticate your user. This will probably be on the login page.

tnsOAuthModule.login()
     .then(()=>{
       console.log('logged in');
     })
     .catch((er)=>{
       console.log(er);
     });

The login function returns a JavaScript Promise object so you can listen for successful login or failures.

You can get to the access token whenever you need to pass it to the API

var token = tnsOAuthModule.accessToken();


Making Authenticated Requests

When you are calling the API of the service you are using, whether it is Office 365, Microsoft Graph, or Facebook, you will need to pass it the access token with every request so it knows who you are, so to speak.

We included a convenience function that will check for token expiration, attempt to get a fresh token from the provider, and reathenticate the user if necessary. This is the ensureValidToken function. You can use it before each of your calls to the API, like this

tnsOAuthModule.ensureValidToken()
     .then((token: string) => {
       //OK to call the API
     })
     .catch((er)=>{
       //log error
     });

Summary

Go on and take advantage of this helpful plugin for NativeScript, especially if you are going to be using Office 365 or the Microsoft Graph API, as those will have a separate TypeScript based SDK out that’s in development as this is being published. Contributions are also welcomed at the project’s GitHub home.