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:
- All users have Read access to the todos.
- 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:
- ReactiveSearch Native, a data-driven UI components library for React Native,
- NodeJS/Express, as a middleware server for authenticating the requests and doing write operations to the database ,
- Auth0, as a hosted authentication service,
- Appbase.io, as a hosted database service.
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.
- 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",
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:
- 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).
- 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.
- 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.
- 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.
Diving into the code
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)
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:
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.
2. Configuring Auth0 Callbacks
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):
- You can find the
- For ios, you can update the
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
3. Handling authentication
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.
4. Passing the screenProps to Update and Delete calls in TodoItem
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.
5. Handling writes
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:
- 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
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. 🙂
- Todos app starter projects for client side and server side
- Todos app final repos for client side and server side
- ReactiveSearch GitHub repo ⭐️
- ReactiveSearch docs
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