search
HomePHP FrameworkThinkPHPHow to use ThinkPHP6's Auth authorization

How to use ThinkPHP6's Auth authorization

Jun 20, 2023 am 08:27 AM
thinkphpauthAuthorize

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.

  1. 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
  1. 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.
  1. 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();
  1. 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();
  1. 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();
  1. 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 thinkacadeSession;
use thinkacadeRequest;
use thinkacadeConfig;
use thinkacadeDb;
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.

  1. 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!

Statement
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
What Are the Key Features of ThinkPHP's Built-in Testing Framework?What Are the Key Features of ThinkPHP's Built-in Testing Framework?Mar 18, 2025 pm 05:01 PM

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.

How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?Mar 18, 2025 pm 04:57 PM

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

What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?Mar 18, 2025 pm 04:54 PM

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

How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?Mar 18, 2025 pm 04:51 PM

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

What Are the Advanced Features of ThinkPHP's Dependency Injection Container?What Are the Advanced Features of ThinkPHP's Dependency Injection Container?Mar 18, 2025 pm 04:50 PM

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

How to Use ThinkPHP for Building Real-Time Collaboration Tools?How to Use ThinkPHP for Building Real-Time Collaboration Tools?Mar 18, 2025 pm 04:49 PM

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

What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?Mar 18, 2025 pm 04:46 PM

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

How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?Mar 18, 2025 pm 04:45 PM

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

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.