The following is the ThinkPHP tutorial column to introduce to you the Thinkphp 6.0 authentication plug-in Think-authz, I hope it will be helpful to friends in need!
This extension requires PHP 7.1 and ThinkPHP 6.0. For TP 5.1, please use Think-Casbin.
Use composer
Installation:
composer require casbin/think-authz
Register the service and add it to the application’s global public file service.php
:
return [ // ... tauthz\TauthzService::class,];
Publish configuration files and database migrations Files:
php think tauthz:publish
This will automatically generate the config/tauthz-rbac-model.conf
and config/tauthz.php
files.
Execute the migration tool (Ensure the database configuration information is correct):
php think migrate:run
This will create a table named rules
.
After successful installation, you can use it like this:
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');
You can Check if a user has a certain permission:
// 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}
It provides a very rich API
to facilitate ## Various operations of #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 Refer to Casbin API (https://casbin.org/ docs/en/management-api).
\tauthz\middleware\Basic::class middleware:
Route::get('news/:id','News/Show') ->middleware(\tauthz\middleware\Basic::class, ['news', 'read']);
The above is the detailed content of About the installation and use of Thinkphp 6.0 authentication plug-in Think-authz. For more information, please follow other related articles on the PHP Chinese website!