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:
The key components that I will be using for the app are:
You can check out a screencast of the app here.
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.
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.
"title": "Writing code",
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.
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:
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:
The final directory structure will look something like this:
android // android related configs
ios // ios related configs
├── 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 container
├── todos.js // APIs for performing writes
constants // Some constants used in the app
types // Todo type to be used with prop-types
utils // 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)
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:
After you’ve cloned the projects you can switch into the client project directory and test it out:
react-native run-ios (or)
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.
We’re using an ejected create-react-native-app template, hence the reason for using
react-nativefor running the app. This is needed by the
react-native-auth0package which I’m using here for authentication purposes.
Auth0 requires the callbacks for
android which you can define in the following manner:
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):
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:
Next, we can update the
AndroidManifest.xml file to have a
singleTask and add another
intent-filter . The file should look something like:
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
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:
/* 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
Next, we’ll add a
CFBundleURLSchemes in the
When you start the app from the starter project, it will look something like the following:
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
/components/TodosContainer.js. You may add the following in the
render function of
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
clientId here. In the
handleLogin method we’re saving the
accessToken along with user
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
react-navigation. It takes these props and makes them available under
We’ll use these in
Now we’ll be able to login by clicking on the login button and save the access token for use.
After the authentication happens, I’m saving the
name in the state of
/components/RootComponent. These are made available to the children components via
screenProps by the
/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.
So far, we have just console logged when invoking the
delete calls. Next, I’ll be using three endpoints to handle writes on the data:
Here’s how we can handle these calls on the client side app. We’ll add these to
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:
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. 🙂
Hope you enjoyed this story. You might also like some related stories I’ve written:
Create your free account to unlock your custom reading experience.