PHP-Casbin 是一个用 PHP 语言打造的轻量级开源访问控制框架( https://github.com/php-casbin... ),目前在 GitHub 开源。PHP-Casbin 采用了元模型的设计思想,支持多种经典的访问控制方案,如基于角色的访问控制 RBAC、基于属性的访问控制 ABAC 等。

Yii-Casbin 是一个专为Yii 2.0定制的Casbin的扩展包( https://github.com/php-casbin... )。

安装

通过composer安装

Yii 2.0项目里,通过composer安装这个扩展:

composer require casbin/yii-adapter

配置

使用此扩展时,需要在你的应用程序配置中配置 Casbin 类:

return [
    //....
    'components' => [
        'casbin' => [
            'class' => '\CasbinAdapter\Yii\Casbin',
            
            /*
             * Yii-casbin model setting.
             */
            'model' => [
                // Available Settings: "file", "text"
                'config_type' => 'file',
                'config_file_path' => '/path/to/casbin-model.conf',
                'config_text' => '',
            ],

            // Yii-casbin adapter .
            'adapter' => '\CasbinAdapter\Yii\Adapter',

            /*
             * Yii-casbin database setting.
             */
            'database' => [
                // Database connection for following tables.
                'connection' => '',
                // CasbinRule tables and model.
                'casbin_rules_table' => '{{%casbin_rule}}',
            ],
        ],
    ]
];

用法

通过casbin组件对Casbin的基本访问:


$casbin = \Yii::$app->casbin;

$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 (true === $casbin->enforce($sub, $obj, $act)) {
    // permit alice to read data1
} else {
    // deny the request, show an error
}

自定义models规则

casbin支持多种models规则:

Supported models.

Casbin

Casbin官方网站:https://casbin.org


JonLee
941 声望19 粉丝

作为一个IT职业人,