paint-brush
Securing a React Native App with Server-side Authenticationby@divyanshu013
31,719 reads
31,719 reads

Securing a React Native App with Server-side Authentication

by Divyanshu MaithaniFebruary 14th, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Authentication is an important concern when building apps. A common use case we come across when building apps is <strong>securing our </strong><a href="https://hackernoon.com/tagged/api" target="_blank"><strong>API</strong></a> in order to accept only authenticated requests, hence preventing misuse.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail

Coin Mentioned

Mention Thumbnail
featured image - Securing a React Native App with Server-side Authentication
Divyanshu Maithani HackerNoon profile picture

The key components in this story: NodeJS, ReactiveSearch, React Native and Auth0

Authentication is an important concern when building apps. A common use case we come across when building apps is securing our API in order to accept only authenticated requests, hence preventing misuse.

In this story, I’ll be using a Todos app built with React Native and explain how to create a secure Node/Express API to handle the Create, Update and Delete operations for the app. This will let the app only allow editing of data by authenticated users. For this post we’ll assume that:

  1. All users have Read access to the todos.
  2. Only an authenticated user has write access for Creating, Updating and Deleting the todos. For brevity, we’ll be considering all the authenticated users to have write access.

The key components that I will be using for the app are:

  1. ReactiveSearch Native, a data-driven UI components library for React Native,
  2. NodeJS/Express, as a middleware server for authenticating the requests and doing write operations to the database ,
  3. Auth0, as a hosted authentication service,
  4. Appbase.io, as a hosted database service.

You can check out a screencast of the app here.

Final app preview

ReactiveSearch

ReactiveSearch is an open-source React and React Native UI components library for Elasticsearch which I’ve co-authored with some awesome people. It provides a variety of React Native components that can connect to any Elasticsearch cluster.

In this story I’ll be expanding on another story I wrote on How to build a real-time todo app with React Native which you may check out if you’re interested in building the starter project which I’ll be using here.

Getting Started

We will use the Todos app built with appbase.io and ReactiveSearch Native as a baseline to build our authenticated Todos app. I’ve already setup starter projects which we’ll use both for client and server side. However, before we dive into the code, I’ll talk about a few concepts.

  • Every Appbase app allows different sets of credentials (read and write) for read and write access control.

  • In this post, we will ensure that client side app can only hold the read credentials for our appbase app and we’ll extract the logic for write operations (for creating, deleting and editing todos) to a Node/Express server. This will allow us to restrict the write access only to authenticated users and also keep the write credentials safe.

  • All the todos will have the following structure:

    { "title": "Writing code", "completed": true, "createdAt": 1518766646430, "name": "divyanshu", "avatar": "https://s.gravatar.com/avatar/33ca46e56260bc7d54b2d7246f9a7052?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fdi.png"}

Before we start building the UI, we’ll need a place to store our todos. For brevity, you can use my app which is hosted on appbase.io or clone it for yourself by following this link and clicking on Clone this App button. This will let you make a copy of the dataset as your own app.

View my app dataset here. You can also clone this to your own app

Authentication Concepts

We’re using Auth0 for handling authentication which uses JWT (JSON Web Tokens) as the access tokens. It comprises three parts header, payload and signature separated by dots(.). A JWT looks like:

xxx.yyy.zzz

The header(xxx) defines the type of token and the algorithm used for hashing. The payload(yyy) contains information about the user and additional metadata. The signature(zzz) is used to verify the sender of the token and ensure the message was not tampered along the way. You can find a more detailed explanation at the JWT introduction guide.

Another popular alternative to using JWT tokens has been managing sessions. However, that introduces statefulness — JWT, being stateless, is a better approach.

The access token once verified tells us that the user is authorized to access the API and forms the basis of our token based authentication system. The authentication flow will look as follows:

  • Each request from the React app to the server will include an access_token that will be verified on the server using Express middleware. When we signup or login via Auth0 we’ll receive an id_token (containing user’s profile information)and an access_token (a credential that can be used by a client to access an API).

App design

  • We will be using Auth0, and create a new native client for our tutorial app. We’ll need the Client ID and Domain in order to configure auth0 in our app. You can get these from your Auth0 dashboard.

Getting Domain and Client Id for the app

  • We’ll also need to add a callback URL in the Allowed Callback URLs section since after authentication the client is redirected back to the callback URL with the token info which we’ll later parse for our use. We’ll come to this part later.

Adding callback URLs for the app

  • Next we’ll need to create a new API for the audience identifier (a unique string value used for configuring auth0 instance in the app) which we’ll use later to verify the access tokens.

Getting the audience identifier

Diving into the code

The final directory structure will look something like this:
















android // android related configsios // ios related configscomponents├── RootComponent.js // Root component for our app├── MainTabNavigator.js // Tab navigation component├── TodosScreen.js // Renders the TodosContainer├── Header.js // Header component├── AddTodo.js // Add todo input├── AddTodoButton.js // Add todo floating button├── TodoItem.js // The todo item├── TodosContainer.js // Todos main containerapi├── todos.js // APIs for performing writesconstants // Some constants used in the apptypes // Todo type to be used with prop-typesutils // Streaming logic goes here

Here are the final repositories so you can refer to them at anytime:

(i) Todos Auth Client (React Native App)

(ii) Todos Auth Server (Node/Express server)

1. Getting the projects ready

We are starting with the Todos app code from this previous post and adding an authentication flow to it. You can use the following repositories as starter project files:

(i) Todos Native Auth Client starter project

(ii) Todos Native Auth Server starter project

After you’ve cloned the projects you can switch into the client project directory and test it out:




npm installnpm startreact-native run-ios (or)react-native run-android

This will start the Todos app (which has the entire logic on client side). Now that everything is up and running, we can start writing the authentication flow code.

Note

We’re using an ejected create-react-native-app template, hence the reason for using react-native for running the app. This is needed by the react-native-auth0 package which I’m using here for authentication purposes.

2. Configuring Auth0 Callbacks

Auth0 requires the callbacks for ios or android which you can define in the following manner:

{PRODUCT_BUNDLE_IDENTIFIER}://divyanshu.auth0.com/ios/{PRODUCT_BUNDLE_IDENTIFIER}/callback

and

{YOUR_APP_PACKAGE_NAME}://divyanshu.auth0.com/android/{YOUR_APP_PACKAGE_NAME}/callback

You can add these to your application’s callback URL via the Auth0 dashboard.

For our case the package name is com.todosnative however you can use your own package name and update the same in android manifest and ios plist files. In the starter files I’ve already added these but if you were to do them by yourself, this is how you may done it (here you can skip to the next step):

  • You can find the AndroidManifest.xml file at /android/app/src/main/AndroidManifest.xml

    package="com.auth0sample"

  • For ios, you can update the Info.plist file at /ios/todosnative/Info.plist

    <key>CFBundleIdentifier</key><string>com.todosnative</string>

The dependency for react-native-auth0 is already present in the starter project. You can run the following command to link all the native dependencies:

react-native link

Next, we can update the AndroidManifest.xml file to have a launchMode of singleTask and add another intent-filter . The file should look something like:

<activity    android:name=".MainActivity"    android:label="@string/app_name"    android:launchMode="singleTask"      android:configChanges="keyboard|keyboardHidden|orientation|screenSize"    android:windowSoftInputMode="adjustResize"><intent-filter>    <action android:name="android.intent.action.MAIN" />    <category android:name="android.intent.category.LAUNCHER" /></intent-filter><intent-filter>    <action android:name="android.intent.action.VIEW" />    <category android:name="android.intent.category.DEFAULT" />    <category android:name="android.intent.category.BROWSABLE" />    <data        android:host="YOUR_AUTH0_DOMAIN"        android:pathPrefix="/android/YOUR_APPLICATION_ID/callback"        android:scheme="YOUR_APPLICATION_ID" /></intent-filter></activity>

You can substitute the stub values with your own auth0 domain and application id.

Next, update the /ios/todosnative/AppDelegate.m file and add the following:

#import <React/RCTLinkingManager.h>

/* Add the following after @implementation AppDelegate */

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{  return [RCTLinkingManager application:application openURL:url                      sourceApplication:sourceApplication annotation:annotation];}

Next, we’ll add a CFBundleURLSchemes in the Info.plist file:

<key>CFBundleURLTypes</key><array>    <dict>        <key>CFBundleTypeRole</key>        <string>None</string>        <key>CFBundleURLName</key>        <string>auth0</string>        <key>CFBundleURLSchemes</key>        <array>            <string>org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)</string>        </array>    </dict></array>

3. Handling authentication

When you start the app from the starter project, it will look something like the following:

Initial version of the app

Note that initially you will not be able to add, delete or update the todo items. We’ll add the methods to handle these operations shortly.

First lets add the login Button in /components/TodosContainer.js. You may add the following in the render function of TodosContainer :









<ScrollView><Buttontitle="Login Button"style={{marginTop: 10,marginBottom: 10}}/>...

Next, we’ll create handlers for login and logout in /components/RootComponent.js and pass them to the child components for use. I’ve added comments in the starter project to identify where we would need to add code.

For authentication, I’m using react-native-auth0. You can use your own Auth0 domain and clientId here. In the handleLogin method we’re saving the accessToken along with user avatar and name in state. The handleLogout method will remove these from the state. All the handlers and state are passed via screenProps to the child components rendered by the MainTabNavigator component which uses [TabNavigator](https://reactnavigation.org/docs/tab-navigator.html) from react-navigation. It takes these props and makes them available under screenProps.

We’ll use these in /components/TodosContainer.js:

Now we’ll be able to login by clicking on the login button and save the access token for use.

After adding authentication

Login screen after clicking on Login button

4. Passing the screenProps to Update and Delete calls in TodoItem

After the authentication happens, I’m saving the accessToken, avatar and name in the state of /components/RootComponent. These are made available to the children components via screenProps by the TabNavigator in /components/MainTabNavigator.js. In the previous step, we already passed the screenProps to the TodoItem component. Next, we’ll update the component to make them pass to the API calls.

5. Handling writes

So far, we have just console logged when invoking the add, update or delete calls. Next, I’ll be using three endpoints to handle writes on the data:

  • POST / to create todos
  • PUT / to update todos
  • DELETE / to delete todos

Here’s how we can handle these calls on the client side app. We’ll add these to /api/todos.js:

One thing you’ll notice here is I’m passing some headers in the fetch calls. I’m using the access token we received earlier and passing it in all the calls. We’ll use this to verify the requests on the server side. The body includes the necessary data for creating, updating or deleting the todos. Also, the calls will not go through if the access token is not present.

Now, for the final missing piece, here’s how I’m handling the requests on the server:

Here the checkJwt middleware verifies the access token on each request using the same audience which we specified on the client side and your domain specified here as the issuer. If the token is absent or invalid the request will be rejected as unauthorized. Now you can fire up the server in a different terminal and you’ll be able to handle writes for your app securely. 🙂

Useful Links

  1. Todos app starter projects for client side and server side
  2. Todos app final repos for client side and server side
  3. ReactiveSearch GitHub repo ⭐️
  4. ReactiveSearch docs

Further Reading

Hope you enjoyed this story. You might also like some related stories I’ve written:


How to build a real-time todo app with React Native_A todo app touches on all the important parts of building any data-driven app, including the Create, Read, Update and…_medium.freecodecamp.org


Building a GitHub Repo Explorer with React and Elasticsearch_Elasticsearch is one of the most popular full-text search engines which allows you to search huge volumes of data…_medium.freecodecamp.org