16
MarLaravel Authz is a package based on the Casbin, an authorization library that supports access control models like ACL, RBAC, ABAC.
If you want to install this package then you have to run this command in the terminal. This will download the package.
composer require casbin/laravel-authz
To publish the config, run the vendor publish command:
php artisan vendor:publish
This will create a new model config file named config/lauthz-rbac-model.conf
and a new lauthz
config file named config/lauthz.php
.
To migrate the migrations, run the migrate command:
php artisan migrate
This will create a new table named rules
.
Quick Start
Once installed you can do stuff like this:
use Enforcer;
// adds permissions to a user
Enforcer::addPermissionForUser('eve', 'articles', 'read');
// adds a role for a user.
Enforcer::addRoleForUser('eve', 'writer');
// adds permissions to a rule
Enforcer::addPolicy('writer', 'articles','edit');
You can check if a user has a permission like this:
// to check if a user has permission
if (Enforcer::enforce("eve", "articles", "edit")) {
// permit eve to edit articles
} else {
// deny the request, show an error
}
It provides a very rich API to facilitate various operations on the Policy:
Gets all roles:
Enforcer::getAllRoles(); // ['writer', 'reader']
Gets all the authorization rules in the policy.:
Enforcer::getPolicy();
Gets the roles that a user has.
Enforcer::getRolesForUser('eve'); // ['writer']
Gets the users that has a role.
Enforcer::getUsersForRole('writer'); // ['eve']
See Casbin API for more APIs.
This package comes with EnforcerMiddleware
, RequestMiddleware
middlewares. You can add them inside your app/Http/Kernel.php
file.
protected $routeMiddleware = [
// ...
// a basic Enforcer Middleware
'enforcer' => \Lauthz\Middlewares\EnforcerMiddleware::class,
// an HTTP Request Middleware
'http_request' => \Lauthz\Middlewares\RequestMiddleware::class,
];
Basic Enforcer Middleware
Then you can protect your routes using middleware rules:
Route::group(['middleware' => ['enforcer:articles,read']], function () {
// pass
});
Other Features & Options
For more details, you can visit its complete documentation and source code on Github.
Published at : 16-03-2022
I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.
Launch project