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!

The article discusses ThinkPHP's built-in testing framework, highlighting its key features like unit and integration testing, and how it enhances application reliability through early bug detection and improved code quality.

Article discusses using ThinkPHP for real-time stock market data feeds, focusing on setup, data accuracy, optimization, and security measures.

The article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges

The article discusses implementing service discovery and load balancing in ThinkPHP microservices, focusing on setup, best practices, integration methods, and recommended tools.[159 characters]

ThinkPHP's IoC container offers advanced features like lazy loading, contextual binding, and method injection for efficient dependency management in PHP apps.Character count: 159

The article discusses using ThinkPHP to build real-time collaboration tools, focusing on setup, WebSocket integration, and security best practices.

ThinkPHP benefits SaaS apps with its lightweight design, MVC architecture, and extensibility. It enhances scalability, speeds development, and improves security through various features.

The article outlines building a distributed task queue system using ThinkPHP and RabbitMQ, focusing on installation, configuration, task management, and scalability. Key issues include ensuring high availability, avoiding common pitfalls like imprope


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

WebStorm Mac version
Useful JavaScript development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.