Tips to handle Authentication in Redux

In the last few days I started to write a big app in react-native using the great redux by @gaeron.

When you start developing big applications one of the first part you will face with is “How do I handle user authentication?”, and here it is how I ended up.

The basic Idea

Since you’ll be mostly facing with REST APIs, I think that the better approach over authentication would be using some sort of JSON Web Token auth (formerly jwt-auth).

So basically we will be posting to a login URL, retrive a token, store it, and post to every HTTP request; but also listen for every HTTP request and automatically discard the current token when we receive a 401 HTTP status as a response, which means that the user is’nt authenticated to view that resource.

Alongside the token, we will be storing the currently logged user data, but we will not trust currently stored user-data, since the end-user can easily change that.

This sentence may be obvious, but if you are a beginner, like I was, heads up and remember that hiding a link does’nt block the user to perform an action, you need to protect your REST endpoint as well, and return a 401 HTTP error when the user is unlogged, and a 403 one when the user has no right to perform that action.

The things to do checklist

  • Create your auth constants
  • Create the action creators
  • Create your auth reducer:
  • You can now use an action creator middleware to automatically append the query parameter ?token= to your REST URL. Here there is what I use internally, it’s simple but it gives you the basic idea of how to handle it!

And you’re done! Checking if the user is logged is done by simply check if the store contains a value for the token, and if not, the user is’nt logged in!

Hope that this post helped you, and let me know if you find out a better way to handle user authentication! :D

Like what you read? Give Mattia Manzati a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.