An authorization library that supports access control models like ACL, RBAC, ABAC in Laravel.

Overview

Laravel Authorization

Laravel-authz is an authorization library for the laravel framework.

Build Status Coverage Status Latest Stable Version Total Downloads License

It's based on Casbin, an authorization library that supports access control models like ACL, RBAC, ABAC.

All you need to learn to use Casbin first.

Installation

Require this package in the composer.json of your Laravel project. This will download the package.

composer require casbin/laravel-authz

The Lauthz\LauthzServiceProvider is auto-discovered and registered by default, but if you want to register it yourself:

Add the ServiceProvider in config/app.php

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

The Enforcer facade is also auto-discovered, but if you want to add it manually:

Add the Facade in config/app.php

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

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

Usage

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
}

Using Enforcer Api

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']

Determines whether a user has a role.

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

Adds a role for a user.

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

Adds a permission for a user or role.

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

Deletes a role for a user.

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

Deletes all roles for a user.

Enforcer::deleteRolesForUser('eve');

Deletes a role.

Enforcer::deleteRole('writer');

Deletes a permission.

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

Deletes a permission for a user or role.

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

Deletes permissions for a user or role.

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

Gets permissions for a user or role.

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

Determines whether a user has a permission.

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

See Casbin API for more APIs.

Using a middleware

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
});

HTTP Request Middleware ( RESTful is also supported )

If you need to authorize a Request,you need to define the model configuration first in config/lauthz-rbac-model.conf:

[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, using middleware rules:

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

Multiple enforcers

If you need multiple permission controls in your project, you can configure multiple enforcers.

In the lauthz file, it should be like this:

return [
    'default' => 'basic',

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

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

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

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

Then you can choose which enforcers to use.

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

Using artisan commands

You can create a policy from a console with artisan commands.

To user:

php artisan policy:add eve,articles,read

To Role:

php artisan policy:add writer,articles,edit

Adds a role for a user:

php artisan role:assign eve writer

Using cache

Authorization rules are cached to speed up performance. The default is off.

Sets your own cache configs in Laravel's config/lauthz.php.

'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,
],

Thinks

Casbin in Laravel. You can find the full documentation of Casbin on the website.

License

This project is licensed under the Apache 2.0 license.

Comments
  • Call to undefined method Casbin\\Enforcer::buildIncrementalRoleLinks()

    Call to undefined method Casbin\\Enforcer::buildIncrementalRoleLinks()

    Starting from v2.2.0 I'm getting the following error while executing Enforcer::deleteRoleForUser

    Call to undefined method Casbin\Enforcer::buildIncrementalRoleLinks()\n#0 /var/www/html/vendor/casbin/casbin/src/ManagementEnforcer.php(582): Casbin\InternalEnforcer->removePolicyInternal()\n#1 /var/www/html/vendor/casbin/casbin/src/ManagementEnforcer.php(540): Casbin\ManagementEnforcer->removeNamedGroupingPolicy()\n#2 /var/www/html/vendor/casbin/casbin/src/Enforcer.php(100): Casbin\ManagementEnforcer->removeGroupingPolicy()\n#3 /var/www/html/app/Observers/Auth/UserAccessGroupObserver.php(65): Casbin\Enforcer->deleteRoleForUser()\n#4 /var/www/html/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(412): ... casbin/casbin version is v3.6.0

    If it's difficult to implement, then it seems "require" in composer.json is not quite correct..

    "require" : { "casbin/casbin": "~3.1", ... }

    opened by rus-ik 14
  • I hope it can be used under the lumen project at the same time?

    I hope it can be used under the lumen project at the same time?

    强烈希望可以同时在lumen项目下使用, 目前我们公司项目大多数都采用的是lumen框架搭建的; 在安装php-casbin/laravel-authz的时候会报错,提示:必须在laravel上才能使用; 强制安装上之后,发现Laravel框架核心也被安装上了, 这样会导致项目vendor目录非常大。 所以希望发个能在lumen上使用的版本,谢谢。

    enhancement 
    opened by dafa168 10
  • Argument 1 passed to Casbin\Rbac\DefaultRoleManager\RoleManager::hasLink() must be of the type string, int given, called in /var/www/html/amitdeveloper28/vendor/casbin/casbin/src/Util/BuiltinOperations.php on line 440

    Argument 1 passed to Casbin\Rbac\DefaultRoleManager\RoleManager::hasLink() must be of the type string, int given, called in /var/www/html/amitdeveloper28/vendor/casbin/casbin/src/Util/BuiltinOperations.php on line 440

    I am getting this issue, when I used following steps to reproduce this issue.

    1. I am using laravel Laravel Framework 6.20.38.
    2. add permission of logged user in laravel. Below are my code: $email = Auth::user()->email; // adds permissions to a user \Enforcer::addPermissionForUser($email, '/photo/index', 'GET');
    3. When, I hit this allow path, I am getting this error:
    4. Argument 1 passed to Casbin\Rbac\DefaultRoleManager\RoleManager::hasLink() must be of the type string, int given, called in /var/www/html/amitdeveloper28/vendor/casbin/casbin/src/Util/BuiltinOperations.php on line 440
    bug released 
    opened by amitgoldy1 7
  • ¿Multiple policy definition?

    ¿Multiple policy definition?

    Hello, I'm on a situation that sometimes I have more parameters for the policies, can this be made like in documentation? I can't figure out the way to make it work. It always tells me I provided less parameters.

    [policy_definition] p = sub, obj, act p2 = sub, act

    Thanks

    opened by bpuig 6
  • Middleware usage?

    Middleware usage?

    Hi, I can't find how to access the authenticated users when applying Enforcer middleware.

    For example I have the following route:

    Route::get('/only-admin', function () { return "You are admin"; })->middleware('enforcer:admin');

    When entering I got an 403 which is ok, but whom is enforcer validating? I don't find a way to relate the User model with Enforcer. Probably I am doing it wrong, how can I do this? Thanks!

    question 
    opened by h-guerrero 6
  • Validation issues in Restful routing style

    Validation issues in Restful routing style

    背景: laravel8+,采取的是restful风格路由,角色绑定路由

    1、在casbin的官网编辑器中示例如下: 1646038097(1)

    2、在laravel插件里配置如下: 1646038214

    3、laravel代码如下: 1646038610(1)

    4、请求结果如下: 1646038626(1) 1646038706(1)

    5、查看日志问题出在regexMatch方法校验。 1646038768(1)

    6、我未重写regexMatch方法。

    谢谢大佬们的指导,拜谢。

    opened by zhengzhishanliang 5
  • Error on php artisan role:assign eve write

    Error on php artisan role:assign eve write

    ErrorException  : Creating default object from empty value
    
      at /var/www/html/vendor/casbin/casbin/src/Model/Policy.php:174
        170|      * @param string[] $rule
        171|      */
        172|     public function addPolicy(string $sec, string $ptype, array $rule): void
        173|     {
      > 174|         $this->items[$sec][$ptype]->policy[] = $rule;
        175|         $this->items[$sec][$ptype]->policyMap[implode(self::DEFAULT_SEP, $rule)] = count($this->items[$sec][$ptype]->policy) - 1;
        176|     }
        177| 
        178|     /**
    
      Exception trace:
    
      1   Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Creating default object from empty value", "/var/www/html/vendor/casbin/casbin/src/Model/Policy.php", ["g", "g"])
          /var/www/html/vendor/casbin/casbin/src/Model/Policy.php:174
    
      2   Casbin\Model\Policy::addPolicy("g", "g")
          /var/www/html/vendor/casbin/casbin/src/InternalEnforcer.php:48
    

    sorry for formatting :) Fresh install on Laravel 6. Migrations created table rules Just tried some artisan commands, the first two created something and the last one php artisan role:assign eve write made an error.

    opened by vadbard 5
  • Get all v2 based on v0,v1,v3 values

    Get all v2 based on v0,v1,v3 values

    I'd like to retrive an array of v2 values based on v0,v1,v3 values, is there a function that I can't find in docs or have I to create a custom Enforcer?

    This is my conf:

    [request_definition]
    r = sub, clt, obj, act
    
    [policy_definition]
    p = sub, clt, obj, act
    
    [role_definition]
    g = _, _
    
    [policy_effect]
    e = some(where (p.eft == allow))
    
    [matchers]
    m = g(r.sub, p.sub) && ((r.clt == p.clt && r.obj == p.obj) || (r.clt == p.clt && r.obj == "*")) && r.act == p.act
    

    Where sub is my user, clt is the table like (posts), obj is the id of obj in ctl and act is my action like index, edit, create, update, store, restore, destroy.

    Can someone help me, pls?

    opened by RafGiammario 3
  • Not Support Laravel8.82.0

    Not Support Laravel8.82.0

    Problem 1 - casbin/psr3-bridge[v1.1.0, ..., v1.2.0] require casbin/casbin ^2.0 -> found casbin/casbin[v2.0.0, ..., v2.4.0] but it conflicts with your root composer.json require (^3.20). - casbin/psr3-bridge v1.3.0 requires psr/log ^1.1 -> found psr/log[1.1.0, ..., 1.1.4] but the package is fixed to 2.0.0 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command. - casbin/laravel-authz v3.1.0 requires casbin/psr3-bridge ^1.1 -> satisfiable by casbin/psr3-bridge[v1.1.0, v1.2.0, v1.3.0]. - Root composer.json requires casbin/laravel-authz ^3.1 -> satisfiable by casbin/laravel-authz[v3.1.0].

    Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.

    Do you need to consider upgrading the version

    opened by shine96 3
  • What if I want to get a new instance?

    What if I want to get a new instance?

    When I use it in workerman, the data I get is always the same,What should I do if I want to get a new instance.

     $policy = Enforcer::getPolicy();
    

    Even if my database has been updated, this method always returns the old data,

    The following method is singleton mode

        /**
         * Attempt to get the enforcer from the local cache.
         *
         * @param string $name
         *
         * @return \Casbin\Enforcer
         *
         * @throws \InvalidArgumentException
         */
        public function guard($name = null)
        {
            $name = $name ?: $this->getDefaultGuard();
    
            if (!isset($this->guards[$name])) {
                $this->guards[$name] = $this->resolve($name);
            }
            return $this->guards[$name];
        }
    
    opened by guoliang1994 3
  • must therefore be declared abstract or implement the remaining methods

    must therefore be declared abstract or implement the remaining methods

    Symfony\Component\ErrorHandler\Error\FatalError: Class Lauthz\Adapters\DatabaseAdapter contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Casbin\Persist\UpdatableAdapter::updatePolicies) in file /web_root/vendor/casbin/laravel-authz/src/Adapters/DatabaseAdapter.php on line 23

    bug released 
    opened by pandelix 3
  • New feature proposal

    New feature proposal

    Now in laravel-authz the artisan commands are really cool and useful and maybe can be make more generic.

    For example, I have this situation for my roles:

    [role_definition] g = _, _ g2 = _, _ g3 = _, _, _ So I ask if it's possible to extends artisan command role:assign to take g,g1,g3 as type parameter, to make easier to insert roles.

    Thanks

    enhancement 
    opened by RafGiammario 3
  • Lauthz\Facades\Enforcer has no type hints

    Lauthz\Facades\Enforcer has no type hints

    Hi,

    Lauthz\Facades\Enforcer has no type hints.

    It is recommended to add @method static.

    `namespace Lauthz\Facades;

    use Illuminate\Support\Facades\Facade;

    /**

    • @see \Casbin\Enforcer
    • @method static array getPermissionsForUser */ class Enforcer extends Facade {`
    enhancement 
    opened by lanrenbulan 3
  • [Question] Loading model from a remote URL

    [Question] Loading model from a remote URL

    Hi,

    I'm storing my model.conf remotly and would like to fetch it at runtime(and eventually cache it)

    I see that the config has a load from string option, I'm wondering how (where) one would set up request call to the model URL and then load the model as string.

    Thank you

    enhancement 
    opened by francoisauclair911 2
Releases(v3.1.3)
Owner
PHP-Casbin
PHP-Casbin authorization library and the official middlewares
PHP-Casbin
An authorization library that supports access control models like ACL, RBAC, ABAC for webman plugin

An authorization library that supports access control models like ACL, RBAC, ABAC for webman plugin

PHP-Casbin 18 Dec 30, 2022
GUI manager for RBAC (Role Base Access Control) Yii2. Easy to manage authorization of user

RBAC Manager for Yii 2 GUI manager for RBAC (Role Base Access Control) Yii2. Easy to manage authorization of user ?? . Documentation Important: If you

MDMunir Software 1.2k Jan 7, 2023
Dynamic ACL is a package that handles Access Control Level on your Laravel Application.

Dynamic ACL Dynamic ACL is a package that handles Access Control Level on your Laravel Application. It's fast to running and simple to use. Install an

yasin 8 Jul 31, 2022
Authentication, authorization and access control for PHP

Jasny Auth Authentication, authorization and access control for PHP. Features Multiple authorization strategies, like groups (for acl) and levels. Aut

Arnold Daniels 105 Dec 12, 2022
A flexible, driver based Acl package for PHP 5.4+

Lock - Acl for PHP 5.4+ I'm sad to say that Lock is currently not maintained. I won't be able to offer support or accept new contributions for the cur

Beatswitch 892 Dec 30, 2022
Tech-Admin is Laravel + Bootstrap Admin Panel With User Management And Access Control based on Roles and Permissions.

Tech-Admin | Laravel 8 + Bootstrap 4 Tech-Admin is Admin Panel With Preset of Roles, Permissions, ACL, User Management, Profile Management. Features M

TechTool India 39 Dec 23, 2022
Register ,Login , Logout , having access control

Helo what's up dude read by the name of creator lov3yp :D This script is inspired by Lov3yp#2018 And Burak karahan Installation steps: !- Import the s

Lov3yp 2 Nov 1, 2021
Middleware to generate access logs for each request using the Apache's access log format

Middleware to generate access logs for each request using the Apache's access log format. This middleware requires a Psr log implementation, for example monolog.

Middlewares 20 Jun 23, 2022
The easiest and most intuitive way to add access management to your Filament Resource Models through `spatie/laravel-permission`

Filament Shield The easiest and most intuitive way to add access management to your Filament Resource Models (more coming soon ?? ) One Plugin to rule

Bezhan Salleh 329 Jan 2, 2023
Authentication and authorization library for Codeigniter 4

Authentication and Authorization Library for CodeIgniter 4. This library provides an easy and simple way to create login, logout, and user registratio

Rizky Kurniawan 12 Oct 10, 2022
Slim Auth is an authorization and authentication library for the Slim Framework.

Slim Auth is an authorization and authentication library for the Slim Framework. Authentication is provided by the Zend Framework Zend\Authentication component, and authorization by the Zend Framework Zend\Permissions\Acl component.

Jeremy Kendall 246 Dec 16, 2022
Declarative style of authorization and validation in laravel.

Laravel Hey Man Readability Counts. In fact, Readability is the primary value of your code !!! ?? Heyman continues where the other role-permission pac

Iman 860 Jan 1, 2023
Minimalistic token-based authorization for Laravel API endpoints.

Bearer Minimalistic token-based authorization for Laravel API endpoints. Installation You can install the package via Composer: composer require ryang

Ryan Chandler 74 Jun 17, 2022
Files Course Laravel Micro Auth and Authorization

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

EspecializaTi 8 Oct 22, 2022
Easy, native Laravel user authorization.

An easy, native role / permission management system for Laravel. Index Installation Migration Customization Model Customization Usage Checking Permiss

DirectoryTree 5 Dec 14, 2022
Manage authorization with granular role-based permissions in your Laravel Apps.

Governor For Laravel Manage authorization with granular role-based permissions in your Laravel apps. Goal Provide a simple method of managing ACL in a

GeneaLabs, LLC 149 Dec 23, 2022
A framework agnostic authentication & authorization system.

Sentinel Sentinel is a PHP 7.3+ framework agnostic fully-featured authentication & authorization system. It also provides additional features such as

Cartalyst 1.4k Dec 30, 2022
It's authorization form, login button handler and login to your personal account, logout button

Authorization-form It's authorization form, login button handler and login to your personal account, logout button Each file is: header.php - html-fil

Galina 2 Nov 2, 2021