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 in order to accept only authenticated requests, hence preventing misuse. securing our API In this story, I’ll be using a and explain how to create a secure Node/Express API to handle the reate, pdate and elete operations for the app. This will let the app only allow editing of data by authenticated users. For this post we’ll assume that: Todos app built with React Native C U D All users have access to the todos. Read Only an authenticated user has write access for , and the todos. For brevity, we’ll be considering all the authenticated users to have write access. Creating Updating Deleting The key components that I will be using for the app are: a data-driven UI components library for React Native, ReactiveSearch Native , as a middleware server for authenticating the requests and doing write operations to the database , NodeJS/Express, , as a hosted authentication service, Auth0 , as a hosted database service. Appbase.io You can check out a screencast of the app . here Final app preview ReactiveSearch is an open-source React and React Native UI components library for Elasticsearch which I’ve co-authored with . It provides a variety of React Native components that can cluster. ReactiveSearch some awesome people connect to any Elasticsearch In this story I’ll be expanding on another story I wrote on which you may check out if you’re interested in building the starter project which I’ll be using here. How to build a real-time todo app with React Native Getting Started We will use the 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. Todos app built with appbase.io and ReactiveSearch Native Every Appbase app allows different sets of credentials ( and ) for . read write read and write access control In this post, we will ensure that client side app can only hold the for our appbase app and we’ll extract the logic for 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 safe. read credentials write write credentials 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 which is hosted on or clone it for yourself by following and clicking on button. This will let you make a copy of the dataset as your own app. my app appbase.io this link Clone this App View my app dataset . You can also clone this to your own app here Authentication Concepts We’re using Auth0 for handling authentication which uses (JSON Web Tokens) as the access tokens. It comprises three parts , and separated by . A JWT looks like: JWT header payload signature dots(.) 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 system. The authentication flow will look as follows: token based authentication Each request from the React app to the server will include an that will be verified on the server using Express middleware. When we signup or login via Auth0 we’ll receive an (containing user’s profile information)and an (a credential that can be used by a client to access an API). access_token id_token access_token App design We will be using , and create a new client for our tutorial app. We’ll need the and in order to configure auth0 in our app. You can get these from your Auth0 . Auth0 native Client ID Domain dashboard Getting Domain and Client Id for the app We’ll also need to add a callback URL in the section since after authentication the client is redirected back to the callback URL with the info which we’ll later parse for our use. We’ll come to this part later. Allowed Callback URLs token Adding callback URLs for the app Next we’ll need to create a new API for the identifier (a unique string value used for configuring auth0 instance in the app) which we’ll use later to verify the access tokens. audience 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) (React Native App) Todos Auth Client (ii) (Node/Express server) Todos Auth Server 1. Getting the projects ready We are starting with the Todos app code from this and adding an authentication flow to it. You can use the following repositories as starter project files: previous post (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 for running the app. This is needed by the package which I’m using here for authentication purposes. react-native react-native-auth0 2. Configuring Auth0 Callbacks Auth0 requires the callbacks for or which you can define in the following manner: ios android {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 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 : com.todosnative (here you can skip to the next step) You can find the file at AndroidManifest.xml /android/app/src/main/AndroidManifest.xml package="com.auth0sample" For ios, you can update the file at Info.plist /ios/todosnative/Info.plist <key>CFBundleIdentifier</key><string>com.todosnative</string> The dependency for is already present in the starter project. You can run the following command to all the native dependencies: react-native-auth0 link react-native link Next, we can update the file to have a of and add another . The file should look something like: AndroidManifest.xml launchMode singleTask intent-filter <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 file and add the following: /ios/todosnative/AppDelegate.m #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 in the file: CFBundleURLSchemes Info.plist <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 in . You may add the following in the function of : Button /components/TodosContainer.js render TodosContainer <ScrollView><Buttontitle="Login Button"style={{marginTop: 10,marginBottom: 10}}/>... Next, we’ll create handlers for login and logout in 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. /components/RootComponent.js For authentication, I’m using . You can use your own Auth0 and here. In the method we’re saving the along with user and in state. The method will remove these from the state. All the handlers and state are passed via to the child components rendered by the component which uses from . It takes these props and makes them available under . react-native-auth0 domain clientId handleLogin accessToken avatar name handleLogout screenProps MainTabNavigator [TabNavigator](https://reactnavigation.org/docs/tab-navigator.html) react-navigation 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 , and in the state of . These are made available to the children components via by the in . In the previous step, we already passed the to the component. Next, we’ll update the component to make them pass to the API calls. accessToken avatar name /components/RootComponent screenProps TabNavigator /components/MainTabNavigator.js screenProps TodoItem 5. Handling writes So far, we have just console logged when invoking the , or calls. Next, I’ll be using three endpoints to handle writes on the data: add update delete to create todos POST / to update todos PUT / to delete todos DELETE / 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 in the 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 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. headers fetch body Now, for the final missing piece, here’s how I’m handling the requests on the server: Here the middleware verifies the access token on each request using the same which we specified on the client side and your specified here as the . 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. 🙂 checkJwt audience domain issuer Useful Links Todos app starter projects for and client side server side Todos app final repos for and client side server side ⭐️ ReactiveSearch GitHub repo ReactiveSearch docs Further Reading Hope you enjoyed this story. You might also like some related stories I’ve written: _A todo app touches on all the important parts of building any data-driven app, including the Create, Read, Update and…_medium.freecodecamp.org How to build a real-time todo app with React Native _Elasticsearch is one of the most popular full-text search engines which allows you to search huge volumes of data…_medium.freecodecamp.org Building a GitHub Repo Explorer with React and Elasticsearch