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

Overview

PHP-Casbin

Scrutinizer Code Quality Default Coverage Status Latest Stable Version Total Downloads License Gitter

Documentation | Tutorials | Extensions

Breaking News: Laravel-authz is now available, an authorization library for the Laravel framework.

PHP-Casbin is a powerful and efficient open-source access control library for PHP projects. It provides support for enforcing authorization based on various access control models.

All the languages supported by Casbin:

golang java nodejs php
Casbin jCasbin node-Casbin PHP-Casbin
production-ready production-ready production-ready production-ready
python dotnet delphi rust
PyCasbin Casbin.NET Casbin4D Casbin-RS
production-ready production-ready experimental production-ready

Installation

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

composer require casbin/casbin

Get started

  1. New a Casbin enforcer with a model file and a policy file:
require_once './vendor/autoload.php';

use Casbin\Enforcer;

$e = new Enforcer("path/to/model.conf", "path/to/policy.csv");
  1. Add an enforcement hook into your code right before the access happens:
$sub = "alice"; // the user that wants to access a resource.
$obj = "data1"; // the resource that is going to be accessed.
$act = "read"; // the operation that the user performs on the resource.

if ($e->enforce($sub, $obj, $act) === true) {
    // permit alice to read data1
} else {
    // deny the request, show an error
}

Table of contents

Supported models

  1. ACL (Access Control List)
  2. ACL with superuser
  3. ACL without users: especially useful for systems that don't have authentication or user log-ins.
  4. ACL without resources: some scenarios may target for a type of resources instead of an individual resource by using permissions like write-article, read-log. It doesn't control the access to a specific article or log.
  5. RBAC (Role-Based Access Control)
  6. RBAC with resource roles: both users and resources can have roles (or groups) at the same time.
  7. RBAC with domains/tenants: users can have different role sets for different domains/tenants.
  8. ABAC (Attribute-Based Access Control): syntax sugar like resource.Owner can be used to get the attribute for a resource.
  9. RESTful: supports paths like /res/*, /res/:id and HTTP methods like GET, POST, PUT, DELETE.
  10. Deny-override: both allow and deny authorizations are supported, deny overrides the allow.
  11. Priority: the policy rules can be prioritized like firewall rules.

How it works?

In php-casbin, an access control model is abstracted into a CONF file based on the PERM metamodel (Policy, Effect, Request, Matchers). So switching or upgrading the authorization mechanism for a project is just as simple as modifying a configuration. You can customize your own access control model by combining the available models. For example, you can get RBAC roles and ABAC attributes together inside one model and share one set of policy rules.

The most basic and simplest model in php-casbin is ACL. ACL's model CONF is:

# Request definition
[request_definition]
r = sub, obj, act

# Policy definition
[policy_definition]
p = sub, obj, act

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

# Matchers
[matchers]
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act

An example policy for ACL model is like:

p, alice, data1, read
p, bob, data2, write

It means:

  • alice can read data1
  • bob can write data2

Features

What php-casbin does:

  1. enforce the policy in the classic {subject, object, action} form or a customized form as you defined, both allow and deny authorizations are supported.
  2. handle the storage of the access control model and its policy.
  3. manage the role-user mappings and role-role mappings (aka role hierarchy in RBAC).
  4. support built-in superuser like root or administrator. A superuser can do anything without explict permissions.
  5. multiple built-in operators to support the rule matching. For example, keyMatch can map a resource key /foo/bar to the pattern /foo*.

What php-casbin does NOT do:

  1. authentication (aka verify username and password when a user logs in)
  2. manage the list of users or roles. I believe it's more convenient for the project itself to manage these entities. Users usually have their passwords, and php-casbin is not designed as a password container. However, php-casbin stores the user-role mapping for the RBAC scenario.

Documentation

https://casbin.org/docs/en/overview

Online editor

You can also use the online editor (http://casbin.org/editor/) to write your php-casbin model and policy in your web browser. It provides functionality such as syntax highlighting and code completion, just like an IDE for a programming language.

Tutorials

https://casbin.org/docs/en/tutorials

Policy management

php-casbin provides two sets of APIs to manage permissions:

  • Management API: the primitive API that provides full support for php-casbin policy management.
  • RBAC API: a more friendly API for RBAC. This API is a subset of Management API. The RBAC users could use this API to simplify the code.

model editor

policy editor

Policy persistence

https://casbin.org/docs/en/adapters

Role manager

https://casbin.org/docs/en/role-managers

Examples

Model Model file Policy file
ACL basic_model.conf basic_policy.csv
ACL with superuser basic_model_with_root.conf basic_policy.csv
ACL without users basic_model_without_users.conf basic_policy_without_users.csv
ACL without resources basic_model_without_resources.conf basic_policy_without_resources.csv
RBAC rbac_model.conf rbac_policy.csv
RBAC with resource roles rbac_model_with_resource_roles.conf rbac_policy_with_resource_roles.csv
RBAC with domains/tenants rbac_model_with_domains.conf rbac_policy_with_domains.csv
ABAC abac_model.conf N/A
RESTful keymatch_model.conf keymatch_policy.csv
Deny-override rbac_model_with_deny.conf rbac_policy_with_deny.csv
Priority priority_model.conf priority_policy.csv

Middlewares

Authz middlewares for web frameworks: https://casbin.org/docs/en/middlewares

Our adopters

https://casbin.org/docs/en/adopters

Contributors

This project exists thanks to all the people who contribute.

Backers

Thank you to all our backers! 🙏 [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

This project is licensed under the Apache 2.0 license.

Contact

If you have any issues or feature requests, please contact us. PR is welcomed.

Comments
  • array_combine(): Both parameters should have an equal number of elements

    array_combine(): Both parameters should have an equal number of elements

    Describe the bug An error occurred while trying to create the RBAC model.

    array_combine(): Both parameters should have an equal number of elements

    Check the error code address and find that the error exists in line CoreEnforcer.php 645

    { "file": "E:\\phpstudy_pro\\WWW\\c.com\\vendor\\casbin\\casbin\\src\\CoreEnforcer.php", "line": 645, "function": "array_combine", "args": [ [ "p_sub", "p_obj", "p_act" ], [ "测试, /admin/setup/wx", "ANY" ] ] }

    It processes "test" and "/ admin / setup / Wx" into one field. The correct one should be

    [ "测试“, ”/admin/setup/wx", "ANY" ]

    ** php version ** 7.3

    ** SQL version ** 5.7.26

    ** casbin version ** casbinPHP V3.19.0

    ** plug-in ** casbin/database-adapter V1.6.0

    opened by 490626721 13
  • I got wrong match result from RBAC model

    I got wrong match result from RBAC model

    laravel-authz, version 3.1.1 php-casbin, version 3.20.3

    conf

    [request_definition]
    r = admin_id, site_id, permission_name
    
    [policy_definition]
    p = group_id, site_id, permission_name
    
    [role_definition]
    g = _, _
    
    [policy_effect]
    e = some(where (p.eft == allow))
    
    [matchers]
    m = g(r.admin_id, p.group_id) && r.site_id == p.site_id && r.permission_name == p.permission_name
    

    if policy like below

    p, 4,2, read
    p, 2,4, read
    
    g, 1, 2
    g2, 2,4
    
    

    request

    Enforcer::enforce('1', '2', 'read'); // true
    

    I think it should be false, but I got true.

    but if I delete last row in policy like this

    p, 4,2, read
    p, 2,4, read
    
    g, 1, 2
    

    request

    Enforcer::enforce('1', '2', 'read'); // false
    

    The request got false that I want it. How to correct the configuration to achieve the results what I need, can someone help me, pls?

    I tried https://casbin.org/casbin-editor/, request got false both policy above.

    question 
    opened by heqichang 11
  • Int type results in multiple entries

    Int type results in multiple entries

    Lets assume this code:

    if (!$m->hasPolicy('g', 'g2', $rule)) {
        $m->addPolicy('g', 'g2', $rule);  
        $e->savePolicy();
    }
    

    If $rule = [ '0', '1' ];, everything works as expected, but if $rule = [ 0, 1 ];, the $m->hasPolicy always evaluates to false. I'm not sure, why php doesn't throw an exception, because https://github.com/php-casbin/php-casbin/blob/ecc5eb20ab6669045b892247b080853483d7a17d/src/Model/Policy.php#L120 requires string and should fail on an int due to declare(strict_types=1); on https://github.com/php-casbin/php-casbin/blob/ecc5eb20ab6669045b892247b080853483d7a17d/src/Model/Policy.php#L3

    Can anyone reproduce this?

    enhancement 
    opened by killua-eu 9
  • Is there an example of FilteredAdapter or implement document ?

    Is there an example of FilteredAdapter or implement document ?

    I am trying yii-permission , and post an issue.

    https://github.com/php-casbin/yii-permission/issues/6

    Becasue every request will query all data from casbin_rule, If i have many domain and user , the result will be very large.

    I think FilteredAdapter may fix the problem , but I can not find any example for php version. Anyone who has implemented it for mysql( or any database ) ? please provide it , thanks.

    question 
    opened by pigochu 9
  • rbac_with_domain_pattern_model can not work with domain *

    rbac_with_domain_pattern_model can not work with domain *

    Hi I am trying examples/rbac_with_domain_pattern_model.conf I load rbac_with_domain_pattern_policy.csv

    I use latest version(2.3.0)

    My code

    <?php require_once './vendor/autoload.php';
    
    use Casbin\Enforcer;
    
    $e = new Enforcer("config/casbin_model.conf", "config/casbin_policy.csv");
    
    $sub = "alice"; // the user that wants to access a resource.
    $obj = "data1"; // the resource that is going to be accessed.
    $dom = "domain1";
    $act = "read"; // the operation that the user performs on the resource.
    
    var_dump($e->enforce($sub, $dom, $obj, $act));
    

    it dump false When I change $sub = "bob" , $dom t="domain2" , $obj="data2" , it dump true. Why alice no perssion ? does this version support wildcard(*) ?

    bug 
    opened by pigochu 9
  • Policy not matching

    Policy not matching

    Hi guys,

    version: casbin/casbin v3.3.0

    here the conf and the policy I am trying to use:

    [request_definition]
    r = sub, dom, act
    
    [policy_definition]
    p = sub, dom, act, eft
    
    [role_definition]
    g = _, _, _
    
    [policy_effect]
    e = some(where (p.eft == allow)) && !some(where (p.eft == deny))
    
    [matchers]
    m = g(r.sub, p.sub, r.dom) && r.dom == p.dom && r.act == p.act
    
    p, admin_domain1, domain1, read, allow
    p, admin_domain1, domain1, write, allow
    p, admin_domain2, domain2, read, allow
    p, admin_domain2, domain2, write, allow
    g, alice, admin_domain1, domain1
    g, bob, admin_domain2, domain2
    

    Now, when I want to test:

            $this->assertTrue($enforcer->enforce('alice', 'domain1', 'read')); // <--- pass
            $this->assertTrue($enforcer->enforce('alice', 'domain1', 'write')); // <--- pass
    
            $this->assertFalse($enforcer->enforce('alice', 'domain2', 'read')); // <--- fail
            $this->assertFalse($enforcer->enforce('alice', 'domain2', 'write')); // <--- fail
    
            $this->assertFalse($enforcer->enforce('bob', 'domain1', 'read')); // <--- fail
            $this->assertFalse($enforcer->enforce('bob', 'domain1', 'write')); // <--- fail
    
            $this->assertTrue($enforcer->enforce('bob', 'domain2', 'read')); // <--- pass
            $this->assertTrue($enforcer->enforce('bob', 'domain2', 'write')); // <--- pass
    

    What is wrong with my workflow? Since alice is not related at all with domain2, the assert should return false, but here, it returns true.

    I tried also with the following matcher: m = r.sub == p.sub && r.dom == p.dom && r.act == p.act but same result

    Thank you for your help.

    bug released 
    opened by mmehira 6
  • An $expression variable is initialized with wrong type which results in fatal error

    An $expression variable is initialized with wrong type which results in fatal error

    https://github.com/php-casbin/php-casbin/blob/8d6d87011f2c024af409d71534197c50c9767491/src/Enforcer.php#L556 A variable $expression is initialized as ExpressionLanguage, and then used as function argument where Expression is required. In most cases it is redefined by value returned from $expressionLanguage->parse(...) method, but in one case it is used unchanged: https://github.com/php-casbin/php-casbin/blob/8d6d87011f2c024af409d71534197c50c9767491/src/Enforcer.php#L636 It results in a fatal error with message:

    Object of class Symfony\Component\ExpressionLanguage\ExpressionLanguage could not be converted to string
    
    bug 
    opened by andbabkin 6
  • dose it support sub domain wildcard (*) ?

    dose it support sub domain wildcard (*) ?

    If I have 5 domains. I want define to :

    • domain/1 : This domain has child domain 2 and 3.
    • domain/1/2
    • domain/1/3
    • domain/4 : This domain has child domain 5
    • domain/4/5

    I want domain/1 admin has full access permision , also has full acess permission on domain/1/* , domain/4 admin has full access on domain/4/*.

    so policy maybe

    p, admin, domain/:domainId, data, read
    p, admin, domain/:domainId, data, write
    p, admin, domain/:domainId/:domainId, data, read
    p, admin, domain/:domainId/:domainId, data, write
    
    g, alice, admin, domain/1
    g, alice, admin, domain/1/*
    g, bob, admin, domain/1/2
    g, mary, admin, domain/1/3
    

    alice has full access permission on domain/1/2 and domain/1/3 , bob only has access on domain/1/2

    Is it possibile ?

    question 
    opened by pigochu 6
  • Storing comments with policies

    Storing comments with policies

    As the authorization gets more complex, it would be nice to add comments/description to i.e. roles. Would it be possible to have $m->addPolicy('g', 'g', $rule, 'this role has a comment'); ? Thanks!

    enhancement 
    opened by killua-eu 5
  • Installation issue

    Installation issue

    I am trying to download the packages by running the following command: composer require casbin/casbin but i got following while running it:

    ./composer.json has been updated
    Loading composer repositories with package information
    Updating dependencies (including require-dev)
    Your requirements could not be resolved to an installable set of packages.
    
      Problem 1
        - The requested package casbin/casbin No version set (parsed as 1.0.0) is satisfiable by casbin/casbin[No version set (parsed as 1.0.0)] but these conflict with your requirements or minimum-stability.
    
    
    Installation failed, reverting ./composer.json to its original content.
    

    Can anyone let me know what is the problem?

    question 
    opened by pockemon 5
  • Enforcement results of the Casbin Editor and the enforce() PHP implementation differ

    Enforcement results of the Casbin Editor and the enforce() PHP implementation differ

    I tried to set up my policies using the Casbin Editor, resulting in the following model:

    See https://casbin.org/casbin-editor/#3QDUJPSUG or code below: Model:

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

    Policy:

    p, role, *, *, action
    g, username, role, *
    

    Request:

    username, domain, object, action
    username, *, object, action
    

    In the online editor, both request statements 1 and 2 get enforcement result "true", as expected. Using the PHP library however, request statement 1 returns "false" using following method:

    (new Casbin\Enforcer())->enforce('username', 'domain', 'object', 'action'); 
    

    I assume that the keyMatch() method is not applied to the group domain wildcard *.

    question 
    opened by ewaldkleefstra 4
  • Cannot use multiple policy rule

    Cannot use multiple policy rule

    Hello, I try to use multiple policies as mentioned in documentation and I got some exceptions.

    Model:

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

    Policy:

    p, alice, data1, read
    p, bob, data2, write
    p2, data_group_admin, write
    
    g, alice, data_group_admin
    g2, data1, data_group
    g2, data2, data_group
    

    PHP:

    <?php
    
    require_once './vendor/autoload.php';
    
    use Casbin\Enforcer;
    use Casbin\Model\Model;
    use Casbin\Persist\Adapters\FileAdapter;
    
    $model = Model::newModelFromFile('casbin/model.conf');
    $adapter = new FileAdapter("casbin/policy.csv");
    $e = new Enforcer($model, $adapter);
    
    var_dump($e->enforce("alice", "write"));
    

    Exception:

    /Users/bastien/PhpstormProjects/testcasbin/vendor/casbin/casbin/src/CoreEnforcer.php:799:
    array(2) {
      [0] =>
      string(5) "alice"
      [1] =>
      string(5) "write"
    }
    PHP Fatal error:  Uncaught Casbin\Exceptions\CasbinException: invalid request size: expected 3, got 2 in /Users/bastien/PhpstormProjects/testcasbin/vendor/casbin/casbin/src/CoreEnforcer.php:618
    Stack trace:
    #0 /Users/bastien/PhpstormProjects/testcasbin/vendor/casbin/casbin/src/CoreEnforcer.php(801): Casbin\CoreEnforcer->enforcing('', Array, 'alice', 'write')
    #1 /Users/bastien/PhpstormProjects/testcasbin/test.php(13): Casbin\CoreEnforcer->enforce('alice', 'write')
    #2 {main}
      thrown in /Users/bastien/PhpstormProjects/testcasbin/vendor/casbin/casbin/src/CoreEnforcer.php on line 618
    
    Fatal error: Uncaught Casbin\Exceptions\CasbinException: invalid request size: expected 3, got 2 in /Users/bastien/PhpstormProjects/testcasbin/vendor/casbin/casbin/src/CoreEnforcer.php on line 618
    
    Casbin\Exceptions\CasbinException: invalid request size: expected 3, got 2 in /Users/bastien/PhpstormProjects/testcasbin/vendor/casbin/casbin/src/CoreEnforcer.php on line 618
    
    Call Stack:
        0.0006     396368   1. {main}() /Users/bastien/PhpstormProjects/testcasbin/test.php:0
        0.0094    1166224   2. Casbin\CoreEnforcer->enforce(...$rvals = variadic('alice', 'write')) /Users/bastien/PhpstormProjects/testcasbin/test.php:13
        0.0094    1166664   3. Casbin\CoreEnforcer->enforcing($matcher = '', $explains = [], ...$rvals = variadic('alice', 'write')) /Users/bastien/PhpstormProjects/testcasbin/vendor/casbin/casbin/src/CoreEnforcer.php:801
    
    question 
    opened by Viously 2
Releases(v3.21.1)
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
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
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
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
EvaOAuth provides a standard interface for OAuth1.0(a) / OAuth2.0 client authorization, it is easy to integrate with any PHP project by very few lines code.

EvaOAuth EvaOAuth provides a standard interface for OAuth1.0 / OAuth2.0 client authorization, it is easy to integrate with any PHP project by very few

AlloVince 256 Nov 16, 2022
EvaOAuth provides a standard interface for OAuth1.0(a) / OAuth2.0 client authorization, it is easy to integrate with any PHP project by very few lines code.

EvaOAuth EvaOAuth provides a standard interface for OAuth1.0 / OAuth2.0 client authorization, it is easy to integrate with any PHP project by very few

AlloVince 261 Jan 17, 2022
Auth is a module for the Yii PHP framework that provides a web user interface for Yii's built-in authorization manager

Auth is a module for the Yii PHP framework that provides a web user interface for Yii's built-in authorization manager (CAuthManager). You can read more about Yii's authorization manager in the framework documentation under Authentication and Authorization.

Christoffer Niska 134 Oct 22, 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
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