Full tutorial originally appeared and is available on Auth0's blog: How to Add Role-Based Access Control (RBAC) to React Apps
- Node + npm
- Auth0 account with application
Clone this repository, then run:
$ npm install
You'll need an Auth0 account to manage authentication. You can sign up for a free Auth0 account here.
Next, set up an Auth0 Application so Auth0 can interface with the React app.
- Go to your Auth0 Dashboard and click the "Create a New Application" button.
- Name your new app (something like
React RBAC
) and select "Single Page Web Applications". - In the Settings for your new Auth0 application app, add
http://localhost:3000/callback
to the Allowed Callback URLs. - At the bottom of the Settings section, click "Show Advanced Settings". Choose the OAuth tab and verify that the JsonWebToken Signature Algorithm is set to "RS256".
- Rename
auth0-variables.js.example
insidesrc/constants/
toauth0-variables.js
. - Paste the auth0 credentials in
auth0-variables.js
.
$ npm start
function (user, context, callback) {
user.app_metadata = user.app_metadata || {};
if (user.email === '[email protected]') {
user.app_metadata.role = 'admin';
} else {
user.app_metadata.role = 'writer';
}
auth0.users.updateAppMetadata(user.user_id, user.app_metadata)
.then(() => {
context.idToken['https://itaditya/role'] = user.app_metadata.role;
callback(null, user, context);
})
.catch((err) => {
callback(err);
});
}