Building Users Authorization in React.

Efikas
2 min readMar 30, 2019

--

Many of the applications we build that require users to log in have both User authentications and authorizations, There are many tutorials online that teaches about User authorizations in React, but I can’t find any that meet my satisfaction.

Let get stated

What is User authorization?

User authorization is the ability of the system to give User access/privileges to some features in your application base on the role or permission given to the user.

There are different ways to create user authorization, Some use the If-Else method which I find dirty and difficult to maintain. This requires wrapping the components with an If block.

Another method which I prefer to use is using the HOC to wrap the components you want to authorize, then passing the authorization requirements to the HOC as props. I love to use the CAN keyword because it makes my code more readable. eg. “CAN user Delete”, “CAN user View”, e.t.c.

Let the coding begins!

The first step is to create the HOC component and create access to your state management system, in my case, I use redux.

The user information from the API looks like this.

Now its time to attach the authorization keywords as props. have to use these four keywords:

  1. hasPermission: This accepts a permission string, and check it against the user permissions to grant access.
  2. hasRole: This accepts a role string and checks if the user has the role to grant access.
  3. hasAny: This accepts an array of permission strings, and check if the user has any of the permission to grant access.
  4. hasAll: This accepts an array of permission and checks if the user has all the required permissions to grant access.

To check for the authorization, we use the isAuthorize method.

Finally, update the render method.

Specify the props types.

That's it.

Now, to attach the authorization to a Create button in your application, you wrap the button with the HOC component, then you are good to go.

--

--

Efikas
Efikas

Written by Efikas

Flutter Enthusiast, Writer, Health Researcher, Affiliate Marketer

No responses yet