ThinkPHP6 is an excellent PHP framework that provides us with many efficient tools and functions. Among them, Auth authorization is a very powerful function that can help us manage permissions in applications. This article will introduce how to use ThinkPHP6's Auth authorization.
- Install the Auth component
First, we need to install the Auth component. Execute the following command in the terminal:
composer require topthink/think-auth
After the installation is completed, we need to add the Auth service provider in the configuration file:
// config/app.php return [ // ... 'providers' => [ // ... thinkuthServiceProvider::class, ], ];
Then, we need to execute the following command to generate the Auth configuration file:
php think auth:config
- Configuring the Auth component
The Auth component can be configured to achieve different permission management requirements. The following is a basic configuration:
// config/auth.php return [ 'auth_on' => true, 'auth_type' => 1, 'auth_group' => 'auth_group', 'auth_group_access' => 'auth_group_access', 'auth_rule' => 'auth_rule', 'auth_user' => 'user', ];
- auth_on: Whether to enable permission authentication, true is on, false is off;
- auth_type: Authentication method, 1 is real-time authentication (that is, the authority is reacquired every time the authority is verified), 2 is login authentication (that is, the user logs in Verify permissions later);
- auth_group: user group data table name;
- auth_group_access: user group details association table name;
- auth_rule: permission rule table;
- auth_user: User information table.
- Create permission rules
Before using Auth authorization, we need to create some permission rules first. Permission rules can control user access to different resources. We need to create an auth_rule table in the database, and then create permission rules by adding records.
// appmodelAuthRule.php namespace appmodel; use thinkModel; class AuthRule extends Model { // }
Next, we need to create the auth_rule table in the database:
CREATE TABLE `auth_rule` ( `id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(100) NOT NULL COMMENT '規(guī)則', `title` VARCHAR(100) NOT NULL COMMENT '規(guī)則名稱', `type` TINYINT(1) UNSIGNED NOT NULL DEFAULT '1' COMMENT '規(guī)則類型', `status` TINYINT(1) UNSIGNED NOT NULL DEFAULT '1' COMMENT '狀態(tài)', `condition` TEXT COMMENT '規(guī)則表達(dá)式', PRIMARY KEY (`id`) ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='權(quán)限規(guī)則表';
Then, we can add some permission rules by:
use appmodelAuthRule; $rule = new AuthRule; $rule->name = 'admin/user/index'; $rule->title = '管理用戶'; $rule->save(); $rule = new AuthRule; $rule->name = 'admin/user/add'; $rule->title = '添加用戶'; $rule->save(); $rule = new AuthRule; $rule->name = 'admin/user/edit'; $rule->title = '編輯用戶'; $rule->save(); $rule = new AuthRule; $rule->name = 'admin/user/del'; $rule->title = '刪除用戶'; $rule->save();
- Create user Group
In addition to permission rules, we also need to create user groups. A user group is a collection of users with the same access rights. We need to create an auth_group table in the database, and then create user groups by adding records.
// appmodelAuthGroup.php namespace appmodel; use thinkModel; class AuthGroup extends Model { // }
Next, we need to create the auth_group table in the database:
CREATE TABLE `auth_group` ( `id` INT NOT NULL AUTO_INCREMENT, `title` VARCHAR(100) NOT NULL COMMENT '組名', `status` TINYINT(1) UNSIGNED NOT NULL DEFAULT '1' COMMENT '狀態(tài)', PRIMARY KEY (`id`) ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='用戶組表';
Then, we can add some user groups by:
use appmodelAuthGroup; $group = new AuthGroup; $group->title = '管理員'; $group->save(); $group = new AuthGroup; $group->title = '普通用戶'; $group->save();
- Create users Group Details
Now, we have created some permission rules and user groups. Next, we need to assign the rules to user groups. We need to create an auth_group_access table in the database, and then create user group details by adding records.
// appmodelAuthGroupAccess.php namespace appmodel; use thinkModel; class AuthGroupAccess extends Model { // }
Next, we need to create the auth_group_access table in the database:
CREATE TABLE `auth_group_access` ( `uid` INT NOT NULL COMMENT '用戶id', `group_id` INT NOT NULL COMMENT '用戶組id', UNIQUE KEY `uid_group_id` (`uid`, `group_id`), KEY `uid` (`uid`), KEY `group_id` (`group_id`) ) ENGINE=INNODB DEFAULT CHARSET=utf8mb4 COMMENT='用戶組明細(xì)表';
Then, we can assign permission rules to user groups in the following way:
use appmodelAuthGroupAccess; $access = new AuthGroupAccess; $access->uid = 1; $access->group_id = 1; $access->save(); $access = new AuthGroupAccess; $access->uid = 2; $access->group_id = 2; $access->save(); $access = new AuthGroupAccess; $access->uid = 3; $access->group_id = 2; $access->save();
- Use Auth Authorization
Now, we have created some permission rules and user groups, and assigned the rules to the user groups. Next, we can use Auth authorization to verify whether the user has access rights.
// 授權(quán)驗(yàn)證 use thinkacadeSession; use thinkacadeRequest; use thinkacadeConfig; use thinkacadeDb; use thinkuthAuth; class BaseController extends Controller { protected function initialize() { parent::initialize(); // 如果用戶未登錄,則跳轉(zhuǎn)到登錄頁面 if (!Session::has('user')) { $this->redirect('/login'); } $uid = Session::get('user.id'); // 如果是超級(jí)管理員,則直接通過權(quán)限驗(yàn)證 if ($uid == Config::get('admin_id')) { return true; } $auth = new Auth; $route = strtolower(Request::controller() . '/' . Request::action()); if (!$auth->check($route, $uid)) { $this->error('無權(quán)限'); } } }
First, we need to get the user login information from the Session. If the user is not logged in, jump to the login page.
Then, we get the uid of the current user. If the current user is a super administrator, the permission verification will be passed directly.
Otherwise, we create an Auth instance and get the route of the current request. Then, we use the Auth check method to verify whether the current user has access rights. If not, a no permission error is thrown.
- Summary
In this article, we learned how to use ThinkPHP6's Auth authorization. We use the Auth component to implement permission management and create some permission rules and user groups. Finally, we use Auth authorization to verify that the user has access rights. If you need more advanced permission management functions, you can achieve this by extending the Auth component.
The above is the detailed content of How to use ThinkPHP6's Auth authorization. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

When we no longer want to continue using the current Win10 Enterprise Edition 2016 Long-Term Service Edition, we can choose to switch to the Professional Edition. The method is also very simple. We only need to change some contents and install the system image. How to change win10 enterprise version 2016 long-term service version to professional version 1. Press win+R, and then enter "regedit" 2. Paste the following path directly in the address bar above: Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WindowsNT\CurrentVersion3 , then find the EditionID and replace the content with "professional" to confirm

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.

ThinkPHP is a high-performance PHP framework with advantages such as caching mechanism, code optimization, parallel processing and database optimization. Official performance tests show that it can handle more than 10,000 requests per second and is widely used in large-scale websites and enterprise systems such as JD.com and Ctrip in actual applications.

Development suggestions: How to use the ThinkPHP framework for API development. With the continuous development of the Internet, the importance of API (Application Programming Interface) has become increasingly prominent. API is a bridge for communication between different applications. It can realize data sharing, function calling and other operations, and provides developers with a relatively simple and fast development method. As an excellent PHP development framework, the ThinkPHP framework is efficient, scalable and easy to use.
