How to use ThinkPHP6's Auth authorization
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 '规则', `title` VARCHAR(100) NOT NULL COMMENT '规则名称', `type` TINYINT(1) UNSIGNED NOT NULL DEFAULT '1' COMMENT '规则类型', `status` TINYINT(1) UNSIGNED NOT NULL DEFAULT '1' COMMENT '状态', `condition` TEXT COMMENT '规则表达式', PRIMARY KEY (`id`) ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='权限规则表';
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 '状态', 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='用户组明细表';
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.
// 授权验证 use thinkacadeSession; use thinkacadeRequest; use thinkacadeConfig; use thinkacadeDb; use thinkuthAuth; class BaseController extends Controller { protected function initialize() { parent::initialize(); // 如果用户未登录,则跳转到登录页面 if (!Session::has('user')) { $this->redirect('/login'); } $uid = Session::get('user.id'); // 如果是超级管理员,则直接通过权限验证 if ($uid == Config::get('admin_id')) { return true; } $auth = new Auth; $route = strtolower(Request::controller() . '/' . Request::action()); if (!$auth->check($route, $uid)) { $this->error('无权限'); } } }
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

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

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)

Hot Topics



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

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.

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.

"Development Suggestions: How to Use the ThinkPHP Framework to Implement Asynchronous Tasks" With the rapid development of Internet technology, Web applications have increasingly higher requirements for handling a large number of concurrent requests and complex business logic. In order to improve system performance and user experience, developers often consider using asynchronous tasks to perform some time-consuming operations, such as sending emails, processing file uploads, generating reports, etc. In the field of PHP, the ThinkPHP framework, as a popular development framework, provides some convenient ways to implement asynchronous tasks.

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.
