Laravel authorization: authorization library supporting ACL, RBAC, ABAC and other models

Time:2020-2-15

Based on caspin, laravel authorization is an authorization library that supports access to multiple access control models (such as ACL, RBAC, ABAC, etc.).
Before that, you need to understandCasbin

install

UseComposerInstallation:

composer require casbin/laravel-authz

Lauthz\LauthzServiceProvideryesauto-discoveredBy default, but if you want to register yourself, you canconfig/app.phpAdd inServiceProvider:

'providers' => [
    /*
     * Package Service Providers...
     */
    Lauthz\LauthzServiceProvider::class,
]

Enforcer facadeAlsoauto-discovered, but if you want to add it manually, in theconfig/app.phpAdd to:

'aliases' => [
    // ...
    'Enforcer' => Lauthz\Facades\Enforcer::class,
]

To publish the configuration, runvendor:publishOrder:

php artisan vendor:publish

This is automatically createdModelconfiguration fileconfig/lauthz-rbac-model.confAnd a newLauthzconfiguration fileconfig/lauthz.php

To migrate a migration, run the migrate command:

php artisan migrate

This will create arulesData sheet.

usage

Quick start

After installation, you can do the following:


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 verify the user’s permissions as follows:

// 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
}

Using enforcer API

It provides a very richAPITo promotePolicyOperations:

Get all roles:

Enforcer::getAllRoles(); // ['writer', 'reader']

Get authorization rules for all roles:

Enforcer::getPolicy();

Get all roles for a user:

Enforcer::getRolesForUser('eve'); // ['writer']

Get all users for a role:

Enforcer::getUsersForRole('writer'); // ['eve']

Determine whether a user has a role:

Enforcer::hasRoleForUser('eve', 'writer'); // true or false

To add a role to a user:

Enforcer::addRoleForUser('eve', 'writer');

To give permission to a user or role:

// to user
Enforcer::addPermissionForUser('eve', 'articles', 'read');
// to role
Enforcer::addPermissionForUser('writer', 'articles','edit');

To delete a user’s role:

Enforcer::deleteRoleForUser('eve', 'writer');

To delete all roles for a user:

Enforcer::deleteRolesForUser('eve');

To delete a single role:

Enforcer::deleteRole('writer');

Delete a permission:

Enforcer::deletePermission('articles', 'read'); // returns false if the permission does not exist (aka not affected).

To delete permissions for a user or role:

Enforcer::deletePermissionForUser('eve', 'articles', 'read');

Delete all permissions for a user or role:

// to user
Enforcer::deletePermissionsForUser('eve');
// to role
Enforcer::deletePermissionsForUser('writer');

Get all permissions for a user or role:

Enforcer::getPermissionsForUser('eve'); // return array

Think whether a user has a certain permission:

Enforcer::hasPermissionForUser('eve', 'articles', 'read');  // true or false

MoreAPIRefer to the caspin API.

Using middleware

The expansion pack hasEnforcerMiddlewareandRequestMiddlewareMiddleware. You can add them to yourapp/Http/Kernel.phpIn the document:

protected $routeMiddleware = [
    // ...
    // a basic Enforcer Middleware
    'enforcer' => \Lauthz\Middlewares\EnforcerMiddleware::class,
    // an HTTP Request Middleware
    'http_request' => \Lauthz\Middlewares\RequestMiddleware::class,
];

Basic enforcer Middleware

They can then be used to protect routes:

Route::group(['middleware' => ['enforcer:articles,read']], function () {
    // pass
});

HTTP request middleware (supporting restful)

If you need to authorize a request, you need to firstconfig/lauthz-rbac-model.confModel configuration defined in:

[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[role_definition]
g = _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = g(r.sub, p.sub) && keyMatch2(r.obj, p.obj) && regexMatch(r.act, p.act)

Then, use middleware rules:

Route::group(['middleware' => ['http_request']], function () {
    Route::resource('photo', 'PhotoController');
});

Multiple decision makers

If you need more than one permission control in your project, you can configure more than oneDecision maker

staylauthzIn the configuration file, you should configure as follows:

return [
    'default' => 'basic',

    'basic' => [
        'model' => [
            // ...
        ],

        'adapter' => Lauthz\Adapters\DatabaseAdapter::class,
        // ...
    ],

    'second' => [
        'model' => [
            // ...
        ],

        'adapter' => Lauthz\Adapters\DatabaseAdapter::class,
        // ...
    ],
];

Then choose which decision maker to use:

Enforcer::guard('second')->enforce("eve", "articles", "edit");

Artisan command line

You can be there.ConsoleUseartisanCommand creation policy:

Add policy to user:

php artisan policy:add eve,articles,read

To add a policy to a role:

php artisan policy:add writer,articles,edit

Assign roles to users:

php artisan role:assign eve writer

cache

cacheTo grant authorizationRules can improve performance. They are off by default.

At laravelconfig/lauthz.phpTo set your own cache configuration:

'cache' => [
    // changes whether Lauthz will cache the rules.
    'enabled' => false,

    // cache store
    'store' => 'default',

    // cache Key
    'key' => 'rules',

    // ttl \DateTimeInterface|\DateInterval|int|null
    'ttl' => 24 * 60,
],

Last

CasbinProject address: https://github.com/php-caspin/php-caspin

Laravel AuthorizationProject address: https://github.com/php-caspin/laravel-authz

You can viewCasbinCasbin docs

Recommended Today

Review of SQL Sever basic command

catalogue preface Installation of virtual machine Commands and operations Basic command syntax Case sensitive SQL keyword and function name Column and Index Names alias Too long to see? Space Database connection Connection of SSMS Connection of command line Database operation establish delete constraint integrity constraint Common constraints NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY DEFAULT […]