Role-based authentication and authorization is an important concept in web application development. It allows you to control what different types of users can and cannot access within your application based on their roles or permissions. In this tutorial, we will explore how to implement role-based authentication and authorization in a React JS application using Node.js for the backend.
Prerequisites
Before we get started, make sure you have Node.js installed on your machine. You can download it from https://nodejs.org/. Also, make sure you have a basic understanding of React JS and Node.js.
Setting Up the Node.js Server
- Create a new folder for your project and navigate to it in your terminal.
- Run the following command to initialize a new Node.js project:
npm init -y
- Install the necessary dependencies by running the following command:
npm install express mongoose body-parser jsonwebtoken
- Create a new file named
server.js
and add the following code to create a simple Express server:const express = require('express'); const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(Server is running on port ${PORT}
);
});
### Setting Up the MongoDB Database
1. Install MongoDB on your machine by following the instructions on the official website: https://docs.mongodb.com/manual/installation/
2. Create a new database named `role-based-auth` by running the following command in the MongoDB shell:
use role-based-auth
### Creating User Roles and Permissions
1. Create a new file named `models.js` and add the following code to define the User model:
```javascript
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
email: {type: String, required: true},
password: {type: String, required: true},
role: {type: String, required: true}
});
const User = mongoose.model('User', userSchema);
module.exports = User;
- Set up the connection to the MongoDB database in the
server.js
file:const mongoose = require('mongoose');
mongoose.connect(‘mongodb://localhost/role-based-auth’, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log(‘Connected to MongoDB’);
}).catch((err) => {
console.error(Failed to connect to MongoDB: ${err}
);
});
3. Create a new file named `roles.js` and add the following code to define the roles and permissions:
```javascript
const ROLES = {
ADMIN: 'admin',
USER: 'user'
};
module.exports = ROLES;
Implement Role-Based Authentication and Authorization in React JS
- Create a new React project by running the following command in your terminal:
npx create-react-app role-based-auth-react
- Install the necessary dependencies for role-based authentication and authorization:
npm install axios react-router-dom
- Set up the routes in the
App.js
file:import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function App() {
return (
);
}
4. Create the login form component:
```javascript
import React, { useState } from 'react';
import axios from 'axios';
function Login() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post('http://localhost:5000/login', {
email,
password
});
localStorage.setItem('token', response.data.token);
// Redirect to the appropriate route based on the user's role
} catch (error) {
console.error(error);
}
};
return (
<form onSubmit={handleSubmit}>
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
<button type="submit">Login</button>
</form>
);
}
-
Implement role-based authorization in the
App.js
file by checking the user’s role stored in the JWT token:function PrivateRoute({ component: Component, ...rest }) { return ( <Route {...rest} render={(props) => { const token = localStorage.getItem('token'); if (!token) { // Redirect to the login page } const user = JSON.parse(atob(token.split('.')[1])); if (user.role !== 'admin') { // Redirect to the home page } return <Component {...props} />; }} /> ); }
- Protect the admin route using the
PrivateRoute
component:<PrivateRoute path="/admin" component={Admin} />
Conclusion
In this tutorial, we have explored how to implement role-based authentication and authorization in a React JS application using Node.js for the backend. By following these steps, you can create a secure and scalable web application that effectively manages user roles and permissions. You can further enhance this implementation by adding more roles, permissions, and features as needed for your application.
axios.defaults.withCredentials = true; its ok
i using token call api, my sidebar always refres
Pleas can you share github link for code sources
can you send me link of signup , sigin page and databse , not visible in the description .
No one saw the spelling mistake ? hmmm 🤔
bro i need to make web application for admin and user app for android how to do that
Thanks a lot 😊
can you share your git?
is there any series for this project ? only one video . I want to make this project.
What if I want to create this for the owner of the website and no user can access this even it tries to change the URL to /login and it re-direct to the main website? how is that possible?
Keep it up broo I will support you
source code pls?
yeah we need the source code
bro lives in a cave
source code?
how to store the roles in session
Thank you for your explanation,
You need to learn more bro, like code-first approach to create your DB
Good luck.
Source code please!!
source code pls !!
Hi