Implementing role-based access control (RBAC) in a web application involves managing user roles and permissions to control access to certain resources or actions. In this example, I'll provide a high-level overview of how you can implement RBAC in a Laravel backend and ReactJS frontend.
User Roles and Permissions:
Define roles and permissions in your Laravel application. You can create a Role
and Permission
model, and use relationships to link them.
bashphp artisan make:model Role -m php artisan make:model Permission -m
Define the relationships in the models.
php// Role.php
public function permissions()
{
return $this->belongsToMany(Permission::class);
}
// Permission.php
public function roles()
{
return $this->belongsToMany(Role::class);
}
Create a migration to handle the role-permission relationship.
bashphp artisan make:migration create_permission_role_table
Implement the migration file with the necessary fields.
php// In the migration file
public function up()
{
Schema::create('permission_role', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('permission_id');
$table->unsignedBigInteger('role_id');
$table->timestamps();
$table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});
}
Middleware for Authorization:
Create a custom middleware for handling role-based access control.
bashphp artisan make:middleware CheckRole
Implement the middleware logic in the CheckRole
middleware class.
php// CheckRole.php
public function handle($request, Closure $next, $role)
{
if (!$request->user() || !$request->user()->hasRole($role)) {
abort(403, 'Unauthorized action.');
}
return $next($request);
}
Register the middleware in the Kernel.php
file.
php// In App\Http\Kernel.php
protected $routeMiddleware = [
// ...
'role' => \App\Http\Middleware\CheckRole::class,
];
Attach Middleware to Routes:
Apply the middleware to the routes that require specific roles.
php// In routes/web.php or routes/api.php
Route::group(['middleware' => 'role:admin'], function () {
// Your routes here
});
User Authentication:
Role-Based Rendering:
Retrieve the user's role from the authentication token.
javascriptconst userRole = getUserRole(); // Implement a function to extract the role from the token
Use the user's role to conditionally render components or views.
jsx// Example in a React component
{userRole === 'admin' && <AdminComponent />}
{userRole === 'user' && <UserComponent />}
These are basic steps to get you started with role-based access control in Laravel and ReactJS. Adjustments and additional features may be needed based on your specific requirements and the complexity of your application.