Home PHP Framework ThinkPHP How to use Auth authentication authority operation in ThinkPHP6?

How to use Auth authentication authority operation in ThinkPHP6?

Jun 12, 2023 am 08:23 AM
thinkphp auth authentication Permission operation

With the development of Internet applications, permission management has become an indispensable part of application development. During the development process, we need to assign different permissions to different users to achieve data security and operation permission control. The Auth authentication permission operation in the ThinkPHP6 framework provides us with a simple and easy-to-use solution.

What is Auth authentication permission operation?

Auth is a permission management plug-in in the ThinkPHP6 framework. It implements a set of efficient and controllable permission management mechanisms by defining and managing roles, users, permissions, rules, etc. Its advantages include simple operation, strong adaptability, high controllability, and good scalability. It is widely used in enterprise-level applications.

Here we explain how to use Auth to implement permission management in ThinkPHP6.

Authentication authority mechanism

Before using Auth, we need to understand its authentication authority mechanism. Its roles, users, permissions, rules and other concepts are defined as follows:

  1. Role: refers to a permission unit that assigns permissions to one or more users.
  2. User: An individual in the system, which can be a real user or a system account.
  3. Permission: refers to the operation behavior authorized for users (or roles), similar to the permission settings in the database.
  4. Rule: refers to setting some restrictions for permissions, such as time period restrictions, restricted IPs, etc.

Specifically, we can define some common permissions as follows:

  1. Menu permissions: refers to access control of a certain menu of the application, which allows different The user sees different menu items.
  2. Operation permissions: refers to access control for a certain operation behavior of the application, which allows different users to have different operation permissions.
  3. Data permissions: refers to controlling access to a certain data in the application, which can restrict users to only see or modify the data associated with them.
  4. Field permissions: refers to access control of a certain field in the application, which can restrict users to only see or modify the fields they are associated with.

Authentication permission operation implementation

With the basic concept of authentication permission mechanism, we can start the Auth authentication permission operation in ThinkPHP6.

  1. Install the Auth plug-in

First we need to ensure that the Auth plug-in has been installed in the application, which can be installed through the following command:

composer require topthink/think-auth
Copy after login
  1. Introduction Auth middleware

Using Auth in an application requires the use of middleware, which is configured in config/middleware.php:

return [
    //全局中间件列表
    'global' => [
            hinkmiddlewareSessionInit::class,
            hinkmiddlewareLoadLangPack::class,
            hinkmiddlewareCheckRequestCache::class,
            hinkmiddlewareSendFile::class,
    ],
    //中间件别名
    'alias' => [
        'auth' =>     hinkmiddlewareAuth::class,
    ],
];
Copy after login
  1. Define permission rules

When initializing the application, we need to define some permission rules, which will be used for permission authentication, for example:

use thinkacadeAuth;

//定义规则
Auth::rule('admin.user/index', 'checkAdmin');
Auth::rule('admin.user/add', 'checkAdmin');
Auth::rule('admin.user/edit', 'checkAdmin');
Auth::rule('admin.user/del', 'checkAdmin');
Copy after login

In the above code, we define basic user management permission rules, Without these permissions, the corresponding controller operations cannot be accessed.

  1. Role and user authorization

We need to authorize roles and users in the application, which can be authorized during application initialization:

//定义角色
Auth::group('admin', function () {
    //设置角色权限
    Auth::setRule([
        'admin.user/index',
        'admin.user/add',
        'admin.user/edit',
        'admin.user/del',
    ]);
});

//定义用户并授权
Auth::user('admin', function () {
    Auth::addToGroup('admin')//添加角色
        ->addPermission(['admin.user/add'])//添加权限
        ->removePermission(['admin.user/del']);//移除权限
});
Copy after login

In In the above code, we define a role named admin and set the corresponding permission rules. Then we defined a user named admin, who has the admin role, authorized the admin.user/add permission, and removed the admin.user/del permission.

  1. Authentication

Before we perform permission authentication, we can first judge roles, users, permissions, etc. in the controller:

use thinkacadeAuth;

class User extends Controller
{
    //进行认证
    public function index()
    {
        //验证用户是否登录,没有登录则跳转到登录页面
        if (!Auth::check()) {
            return redirect('admin/auth/login');
        }

        //验证是否为超级管理员,是则直接放行
        if (Auth::isSuperAdmin()) {
            return $this->view->assign('username', Auth::getUser()['username'])->fetch();
        }

        //验证是否为管理员角色,是则验证权限,否则跳转到其他页面
        if (Auth::group('admin')->check()) {
            if (Auth::check('admin.user/index')) {
                return $this->view->assign('username', Auth::getUser()['username'])->fetch();
            } else {
                return redirect('admin/index/model_error');
            }
        } else {
            return redirect('admin/index/role_error');
        }
    }
}
Copy after login

In the above code, we perform user login verification, super administrator verification, role and permission verification, etc., and finally return to the corresponding page or jump.

Summary

Through the above operations, we can use the Auth authentication permission operation in the ThinkPHP6 framework to achieve simple, efficient, and controllable application permission management to ensure data security and operation permission control. During use, in order to ensure the security of the application, we need to carefully set various permission rules, limit the corresponding user and role permissions, and improve the scalability and controllability of the application.

The above is the detailed content of How to use Auth authentication authority operation in ThinkPHP6?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

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.

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

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.

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

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.

Which one is better, laravel or thinkphp? Which one is better, laravel or thinkphp? Apr 09, 2024 pm 03:18 PM

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 Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Nov 22, 2023 pm 12:01 PM

"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.

How to install thinkphp How to install thinkphp Apr 09, 2024 pm 05:42 PM

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.

How is the performance of thinkphp? How is the performance of thinkphp? Apr 09, 2024 pm 05:24 PM

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 Development suggestions: How to use the ThinkPHP framework for API development Nov 22, 2023 pm 05:18 PM

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.

See all articles