Skip to content

Commit 40ccbdb

Browse files
committed
docs: update README with new Yii Authorization features and usage examples
1 parent acce62a commit 40ccbdb

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

README.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,64 @@ Determines whether a user has a permission.
188188
$permission->hasPermissionForUser('eve', 'articles', 'read'); // true or false
189189
```
190190

191+
### Using Yii Authorization
192+
193+
It allows you to integrate Yii's authorization with the Casbin permission management system.
194+
195+
**(1) AccessChecker**
196+
197+
Add the accessChecker configuration in your application's `config/web.php` file:
198+
199+
```php
200+
$config = [
201+
'components' => [
202+
'user' => [
203+
...
204+
'accessChecker' => 'yii\permission\components\PermissionChecker',
205+
]
206+
];
207+
```
208+
209+
Once configured, you can use the `can()` method to check if a user has permission to perform certain actions:
210+
211+
```php
212+
$user->can('acrticles,read');
213+
```
214+
215+
**(2) Behaviors**
216+
217+
The `PermissionControl` behavior allows you to enforce permission checks at the controller level. Add the PermissionControl behavior to your controller's behaviors() method:
218+
219+
```php
220+
public function behaviors()
221+
{
222+
return [
223+
'permission' => [
224+
'class' => \yii\permission\components\PermissionControl::class,
225+
'user' => $user, // optional, defaults to \Yii::$app->user
226+
'only' => ['read-articles', 'write-articles'],
227+
'policy' => [
228+
[
229+
'allow' => true,
230+
'actions' => ['read-articles'],
231+
'enforce' => ['articles', 'read']
232+
],
233+
[
234+
'allow' => true,
235+
'actions' => ['write-articles'],
236+
'enforce' => ['articles', 'write']
237+
]
238+
],
239+
'denyCallback' => function ($policy, $action) {
240+
// custom action when access is denied
241+
} // optional, defaults to throwing an exception
242+
]
243+
];
244+
}
245+
```
246+
247+
**Note:** Additionally,You can also configure a `denyCallback` for each `policy`, which will be invoked when the user does not meet the required permission. This callback takes precedence. The configuration is similar to Yii's official [AccessControl](https://www.yiiframework.com/doc/guide/2.0/zh-cn/security-authorization#access-control-filter).
248+
191249
See [Casbin API](https://casbin.org/docs/en/management-api) for more APIs.
192250

193251
## Define your own model.conf

0 commit comments

Comments
 (0)