The essential boilerplate to authenticate users on your React-Native app

Disclaimer

  • I will be demonstrating the authentication using a simplified version of OAuth2, with a long-live refresh token and short-live access token. To simplify the example, the Resource server and the Authorization server are the same entity. If you want to know more about mobile security, I suggest you read this article: https://stormpath.com/blog/the-ultimate-guide-to-mobile-api-security
  • The scope of the project is generic enough to let anyone adapt it to their own need. You might need to make changes in order to get everything production ready.

The idea

Server API entry-points

  • POST /clients
  • POST /users: Create a new user
  • POST /users/auth: Authenticate and retrieve the access and refresh tokens in exchange of email/password
  • POST /users/auth/refresh: Authenticate and retrieve the access token in exchange of the refresh token.
  • GET /users: Retrieve the list of users
  • POST /users/auth/revoke: Log out, revoke access by destroying the user tokens

Setup your React-Native application

  • components: global components that can be used anywhere in your application.
  • data: takes care of fetching and saving the data on the Redux store as needed. The scenes are usually the ones consuming data.
  • scenes: your application scenes
  • services: self-contained modules “helpers” that cannot be assimilated as components.
  • The App.js is the bootstrap of the application. It will by default load the Splash scene and try to auto-login the user. Then, transition to the right scene.
  • Finally, the store.js imports the reducers and creates the Redux store. It exports a singleton that can be used anywhere in the client.

React-Native toolkit

Interacting with the API

  • For non-protected resources the API expects the client to send the Client-ID as part of the header.
  • For protected resources the API expects the client to send the Authorization header which will have the access token as a Bearer.
/src/services/api/config.js
/src/services/api/index.js

Create a new user

/src/data/users/api.js

Authenticate and keep the user logged-in

/src/services/session/api.js
/src/services/session/index.js
/src/services/session/index.js
/src/services/session/index.js

Bring everything together

App startup

/src/App.js

Login

/src/scenes/Main/scenes/Login/index.js

Register

/src/scenes/Main/scenes/Register/index.js

Logout

/src/scenes/Main/scenes/Users/index.js

Wrapping up

More articles from me

About me

--

--

Front-end Application Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store