PHPackages                             casbin/think-authz - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. casbin/think-authz

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

casbin/think-authz
==================

An authorization library that supports access control models like ACL, RBAC, ABAC for ThinkPHP.

v2.0.4(1y ago)27918.5k↓21%506Apache-2.0PHPPHP &gt;=8.0CI passing

Since Oct 24Pushed 1y ago13 watchersCompare

[ Source](https://github.com/php-casbin/think-authz)[ Packagist](https://packagist.org/packages/casbin/think-authz)[ RSS](/packages/casbin-think-authz/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (6)Versions (25)Used By (6)

 ThinkPHP Authorization
========================

[](#----thinkphp-authorization)

 **Think-authz 是一个专为 ThinkPHP 打造的授权（角色和权限控制）工具**

 [ ![Build Status](https://github.com/php-casbin/think-authz/actions/workflows/phpunit.yml/badge.svg) ](https://github.com/php-casbin/think-authz/actions/workflows/phpunit.yml) [ ![Coverage Status](https://camo.githubusercontent.com/cfbf29d3fd5559800ebcb95fe1e1ca0e1b2825211e38276eeeff7299dcde9c39/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f7068702d63617362696e2f7468696e6b2d617574687a2f62616467652e737667) ](https://coveralls.io/github/php-casbin/think-authz) [ ![Latest Stable Version](https://camo.githubusercontent.com/3a16a289cf14e65da282b463d63e566e2c81bf5b03408ec26a23dd9804e38a1f/68747470733a2f2f706f7365722e707567782e6f72672f63617362696e2f7468696e6b2d617574687a2f762f737461626c65) ](https://packagist.org/packages/casbin/think-authz) [ ![Total Downloads](https://camo.githubusercontent.com/c7c9cb7ee77833142003661cadab0c4b4606906d13e3c659543dec0f2101baeb/68747470733a2f2f706f7365722e707567782e6f72672f63617362696e2f7468696e6b2d617574687a2f646f776e6c6f616473) ](https://packagist.org/packages/casbin/think-authz) [ ![License](https://camo.githubusercontent.com/8423c61ab04edfe12b0af04eca29d411912445dd5e969555fe26e1ff9797ed7f/68747470733a2f2f706f7365722e707567782e6f72672f63617362696e2f7468696e6b2d617574687a2f6c6963656e7365) ](https://packagist.org/packages/casbin/think-authz)

它基于 [PHP-Casbin](https://github.com/php-casbin/php-casbin), 一个强大的、高效的开源访问控制框架，支持基于`ACL`, `RBAC`, `ABAC`等访问控制模型。

在这之前，你需要了解 [Casbin](https://github.com/php-casbin/php-casbin) 的相关知识。

- [安装](#%E5%AE%89%E8%A3%85)
- [用法](#%E7%94%A8%E6%B3%95)
    - [快速开始](#%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B)
    - [使用 Enforcer Api](#%E4%BD%BF%E7%94%A8-enforcer-api)
    - [使用中间件](#%E4%BD%BF%E7%94%A8%E4%B8%AD%E9%97%B4%E4%BB%B6)
- [感谢](#thinks)
- [License](#license)

安装
--

[](#安装)

使用`composer`安装：

```
composer require casbin/think-authz

```

注册服务，在应用的全局公共文件`service.php`中加入：

```
return [
    // ...

    tauthz\TauthzService::class,
];
```

发布配置文件和数据库迁移文件：

```
php think tauthz:publish

```

这将自动生成 `config/tauthz-rbac-model.conf` 和 `config/tauthz.php` 文件。

执行迁移工具（**确保数据库配置信息正确**）：

```
php think migrate:run

```

这将创建名为 `rules` 的表。

用法
--

[](#用法)

### 快速开始

[](#快速开始)

安装成功后，可以这样使用:

```
use tauthz\facade\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');
```

你可以检查一个用户是否拥有某个权限:

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

### 使用 Enforcer Api

[](#使用-enforcer-api)

它提供了非常丰富的 `API`，以促进对 `Policy` 的各种操作：

获取所有角色:

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

获取所有的角色的授权规则：

```
Enforcer::getPolicy();
```

获取某个用户的所有角色：

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

获取某个角色的所有用户：

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

决定用户是否拥有某个角色：

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

给用户添加角色：

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

赋予权限给某个用户或角色：

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

删除用户的角色：

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

删除某个用户的所有角色：

```
Enforcer::deleteRolesForUser('eve');
```

删除单个角色：

```
Enforcer::deleteRole('writer');
```

删除某个权限：

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

删除某个用户或角色的权限：

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

删除某个用户或角色的所有权限：

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

获取用户或角色的所有权限：

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

决定某个用户是否拥有某个权限

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

更多 `API` 参考 [Casbin API](https://casbin.org/docs/en/management-api) 。

### 使用中间件

[](#使用中间件)

该扩展包带有一个 `\tauthz\middleware\Basic::class` 中间件:

```
Route::get('news/:id','News/Show')
	->middleware(\tauthz\middleware\Basic::class, ['news', 'read']);
```

### 缓存配置

[](#缓存配置)

该扩展包通过配置 `config/tauthz.php` 中的 `cache` 选项来开启或关闭缓存，以及配置缓存标识和过期时间。

通过继承 `tauthz\cache\CacheHandler` 可以实现自定义缓存策略。例如：

```
class MyCacheHandler extends CacheHandler
{
    public function cachePolicies(Rule $model)
    {
        return $model->cacheAlways('my_cache_key', 3600);
    }
}
```

并在 `cache` 配置选项中的`handler`声明此类。

感谢
--

[](#感谢)

[Casbin](https://github.com/php-casbin/php-casbin)，你可以查看全部文档在其 [官网](https://casbin.org/) 上。

License
-------

[](#license)

This project is licensed under the [Apache 2.0 license](LICENSE).

###  Health Score

52

—

FairBetter than 96% of packages

Maintenance49

Moderate activity, may be stable

Popularity47

Moderate usage in the ecosystem

Community30

Small or concentrated contributor base

Maturity72

Established project with proven stability

 Bus Factor1

Top contributor holds 73.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~92 days

Recently: every ~49 days

Total

23

Last Release

369d ago

Major Versions

v1.8.0 → v2.0.02024-10-29

### Community

Maintainers

![](https://www.gravatar.com/avatar/f32cb7625515c0969fec15915be4a137f057c3484420bb7abf025c8e975dd3a5?d=identicon)[leeqvip](/maintainers/leeqvip)

---

Top Contributors

[![leeqvip](https://avatars.githubusercontent.com/u/35752209?v=4)](https://github.com/leeqvip "leeqvip (41 commits)")[![basakest](https://avatars.githubusercontent.com/u/47746206?v=4)](https://github.com/basakest "basakest (6 commits)")[![Tinywan](https://avatars.githubusercontent.com/u/14959876?v=4)](https://github.com/Tinywan "Tinywan (3 commits)")[![qeq66](https://avatars.githubusercontent.com/u/19647183?v=4)](https://github.com/qeq66 "qeq66 (2 commits)")[![Dobmod](https://avatars.githubusercontent.com/u/33273950?v=4)](https://github.com/Dobmod "Dobmod (2 commits)")[![zhanghangt](https://avatars.githubusercontent.com/u/822647?v=4)](https://github.com/zhanghangt "zhanghangt (1 commits)")[![zhangyue0503](https://avatars.githubusercontent.com/u/19261189?v=4)](https://github.com/zhangyue0503 "zhangyue0503 (1 commits)")

---

Tags

access-controlaclauthorizationauthrizationcasbinpermissionsrbacrolesthinkphpauthorizationaclpermissionrbacaccess-controlabaccasbinthinkphpauthz

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/casbin-think-authz/health.svg)

```
[![Health](https://phpackages.com/badges/casbin-think-authz/health.svg)](https://phpackages.com/packages/casbin-think-authz)
```

###  Alternatives

[casbin/laravel-authz

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

324339.9k4](/packages/casbin-laravel-authz)[casbin/casbin

a powerful and efficient open-source access control library for php projects.

1.3k1.4M54](/packages/casbin-casbin)[casbin/webman-permission

webman casbin permission plugin

523.4k2](/packages/casbin-webman-permission)[casbin/codeigniter-permission

Associate users with roles and permissions, use Casbin in CodeIgniter4 Web Framework.

443.0k](/packages/casbin-codeigniter-permission)[hosseinhezami/laravel-permission-manager

Advanced permission manager for Laravel.

403.3k](/packages/hosseinhezami-laravel-permission-manager)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
