Home >PHP Framework >ThinkPHP >How to use ThinkPHP6's Auth authorization

How to use ThinkPHP6's Auth authorization

PHPz
PHPzOriginal
2023-06-20 08:27:131477browse

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