Before we begin this, please assume the following:
- We will discuss about Authorization and not Authentication (Authorization is not Authentication).
- Our React App is storing Logged-In user’s Role in localStorage(you can put it anywhere in the browser).
Let’s build the basement first… 🏃 🏃🏃🏃🏃
- HOC (Higher-Order Component):
The word sounds so cool 🆒 but it is little bit confusing as it’s not exactly a component but a function. ️
You heard it right, Higher-Order Component is a function and not a component. Let me show you it’s definition:
A higher-order component is a function that takes a component and returns a new component.
HOCs are functions to which we pass our components and they can bring some transformation to it and return back a new component. If you have ever used Redux or Material-UI, you would have seen something like connect and withStyles. Connect and withStyles are HOCs which transforms our component and returns back a new component. If we talk specifically about connect, it injects props in our component which we name as mapDispatchToProps and mapStateToProps.
Did you just say something like map??? map can also be assumed as a HOC which takes an array and return a transformed array.
2. I assume you have basic knowledge of React, so let’s jump directly into Authorizing our React Components. Many a times, we have requirement to hide something from a normal user but show it to Admins. This is what we call authorization, where we show different pages of our application to different types of users based on his/her role in our application.
Let’s say, we have a <ServerMonitor /> component which we don’t want to show to normal users and only to Admins. So we will create a HOC for authorizing our components to which we can pass any component we want to authorize.
The HOC that we will build is withAuthorization which will take only one parameter, that is the component which we want to authorize.
The withAuthorization HOC is not so fancy, it is just checking if the current_user is Admin, then allow the component to render else send null to prevent the component from rendering.
Next, we will see how to use withAuthorization in our React Components 👊👊
Here in the above snippet, we are passing our ServerMonitor component to the withAuthorization HOC and exporting the returned value. If the current_user is an admin then the same component is returned and hence is exported else null is returned and exported which leads to preventing the ServerMonitor component from rendering in the DOM.
Caveat 😢 😢
Here we are authorizing the components based on UserRole stored in the localStorage which can be changed easily and can be replaced with Admin or anything. So we should have Authorization in our Back-end too in order to prevent data getting exposed to anyone trying to tamper the localStorage.
Thanks for reading it till the end. Hope it helped you and you enjoyed it. 😍 😍