ThinkPHP權(quán)限認(rèn)證Auth實(shí)例詳解
本文以實(shí)例代碼的形式深入剖析了ThinkPHP權(quán)限認(rèn)證Auth的實(shí)現(xiàn)原理與方法,具體步驟如下:
mysql數(shù)據(jù)庫(kù)部分sql代碼:
-- ----------------------------
-- Table structure for think_auth_group
-- ----------------------------
DROP TABLE IF EXISTS `think_auth_group`;
CREATE TABLE `think_auth_group` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`title` char(100) NOT NULL DEFAULT '',
`status` tinyint(1) NOT NULL DEFAULT '1',
`rules` char(80) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='用戶(hù)組表';
-- ----------------------------
-- Records of think_auth_group
-- ----------------------------
INSERT INTO `think_auth_group` VALUES ('1', '管理組', '1', '1,2');
-- ----------------------------
-- Table structure for think_auth_group_access
-- ----------------------------
DROP TABLE IF EXISTS `think_auth_group_access`;
CREATE TABLE `think_auth_group_access` (
`uid` mediumint(8) unsigned NOT NULL COMMENT '用戶(hù)id',
`group_id` mediumint(8) unsigned NOT NULL COMMENT '用戶(hù)組id',
UNIQUE KEY `uid_group_id` (`uid`,`group_id`),
KEY `uid` (`uid`),
KEY `group_id` (`group_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='用戶(hù)組明細(xì)表';
-- ----------------------------
-- Records of think_auth_group_access
-- ----------------------------
INSERT INTO `think_auth_group_access` VALUES ('1', '1');
INSERT INTO `think_auth_group_access` VALUES ('1', '2');
-- ----------------------------
-- Table structure for think_auth_rule
-- ----------------------------
DROP TABLE IF EXISTS `think_auth_rule`;
CREATE TABLE `think_auth_rule` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`name` char(80) NOT NULL DEFAULT '' COMMENT '規(guī)則唯一標(biāo)識(shí)',
`title` char(20) NOT NULL DEFAULT '' COMMENT '規(guī)則中文名稱(chēng)',
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '狀態(tài):為1正常,為0禁用',
`type` char(80) NOT NULL,
`condition` char(100) NOT NULL DEFAULT '' COMMENT '規(guī)則表達(dá)式,為空表示存在就驗(yàn)證,不為空表示按照條件驗(yàn)證',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT='規(guī)則表';
-- ----------------------------
-- Records of think_auth_rule
-- ----------------------------
INSERT INTO `think_auth_rule` VALUES ('1', 'Home/index', '列表', '1', 'Home', '');
INSERT INTO `think_auth_rule` VALUES ('2', 'Home/add', '添加', '1', 'Home', '');
INSERT INTO `think_auth_rule` VALUES ('3', 'Home/edit', '編輯', '1', 'Home', '');
INSERT INTO `think_auth_rule` VALUES ('4', 'Home/delete', '刪除', '1', 'Home', '');
DROP TABLE IF EXISTS `think_user`;
CREATE TABLE `think_user` (
`id` int(11) NOT NULL,
`username` varchar(30) DEFAULT NULL,
`password` varchar(32) DEFAULT NULL,
`age` tinyint(2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of think_user
-- ----------------------------
INSERT INTO `think_user` VALUES ('1', 'admin', '21232f297a57a5a743894a0e4a801fc3', '25');
配置文件Application\Common\Conf\config.php部分:
<?php return array( //'配置項(xiàng)'=>'配置值' 'DB_DSN' => '', // 數(shù)據(jù)庫(kù)連接DSN 用于PDO方式 'DB_TYPE' => 'mysql', // 數(shù)據(jù)庫(kù)類(lèi)型 'DB_HOST' => 'localhost', // 服務(wù)器地址 'DB_NAME' => 'thinkphp', // 數(shù)據(jù)庫(kù)名 'DB_USER' => 'root', // 用戶(hù)名 'DB_PWD' => 'root', // 密碼 'DB_PORT' => 3306, // 端口 'DB_PREFIX' => 'think_', // 數(shù)據(jù)庫(kù)表前綴 'AUTH_CONFIG' => array( 'AUTH_ON' => true, //認(rèn)證開(kāi)關(guān) 'AUTH_TYPE' => 1, // 認(rèn)證方式,1為時(shí)時(shí)認(rèn)證;2為登錄認(rèn)證。 'AUTH_GROUP' => 'think_auth_group', //用戶(hù)組數(shù)據(jù)表名 'AUTH_GROUP_ACCESS' => 'think_auth_group_access', //用戶(hù)組明細(xì)表 'AUTH_RULE' => 'think_auth_rule', //權(quán)限規(guī)則表 'AUTH_USER' => 'think_user'//用戶(hù)信息表 ) );
項(xiàng)目Home控制器部分Application\Home\Controller\IndexController.class.php代碼:
<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
public function index() {
$Auth = new \Think\Auth();
//需要驗(yàn)證的規(guī)則列表,支持逗號(hào)分隔的權(quán)限規(guī)則或索引數(shù)組
$name = MODULE_NAME . '/' . ACTION_NAME;
//當(dāng)前用戶(hù)id
$uid = '1';
//分類(lèi)
$type = MODULE_NAME;
//執(zhí)行check的模式
$mode = 'url';
//'or' 表示滿(mǎn)足任一條規(guī)則即通過(guò)驗(yàn)證;
//'and'則表示需滿(mǎn)足所有規(guī)則才能通過(guò)驗(yàn)證
$relation = 'and';
if ($Auth->check($name, $uid, $type, $mode, $relation)) {
die('認(rèn)證:成功');
} else {
die('認(rèn)證:失敗');
}
}
}
以上這些代碼就是最基本的驗(yàn)證代碼示例。
下面是源碼閱讀:
1、權(quán)限檢驗(yàn)類(lèi)初始化配置信息:
$Auth = new \Think\Auth();
創(chuàng)建一個(gè)對(duì)象時(shí)程序會(huì)合并配置信息
程序會(huì)合并Application\Common\Conf\config.php中的AUTH_CONFIG數(shù)組
public function __construct() {
$prefix = C('DB_PREFIX');
$this->_config['AUTH_GROUP'] = $prefix . $this->_config['AUTH_GROUP'];
$this->_config['AUTH_RULE'] = $prefix . $this->_config['AUTH_RULE'];
$this->_config['AUTH_USER'] = $prefix . $this->_config['AUTH_USER'];
$this->_config['AUTH_GROUP_ACCESS'] = $prefix . $this->_config['AUTH_GROUP_ACCESS'];
if (C('AUTH_CONFIG')) {
//可設(shè)置配置項(xiàng) AUTH_CONFIG, 此配置項(xiàng)為數(shù)組。
$this->_config = array_merge($this->_config, C('AUTH_CONFIG'));
}
}
2、檢查權(quán)限:
check($name, $uid, $type = 1, $mode = 'url', $relation = 'or')
大體分析一下這個(gè)方法
首先判斷是否關(guān)閉權(quán)限校驗(yàn) 如果配置信息AUTH_ON=>false 則不會(huì)進(jìn)行權(quán)限驗(yàn)證 否則繼續(xù)驗(yàn)證權(quán)限
if (!$this->_config['AUTH_ON']) {
return true;
}
獲取權(quán)限列表之后會(huì)詳細(xì)介紹:
$authList = $this->getAuthList($uid, $type);
此次需要驗(yàn)證的規(guī)則列表轉(zhuǎn)換成數(shù)組:
if (is_string($name)) {
$name = strtolower($name);
if (strpos($name, ',') !== false) {
$name = explode(',', $name);
} else {
$name = array($name);
}
}
所以$name參數(shù)是不區(qū)分大小寫(xiě)的,最終都會(huì)轉(zhuǎn)換成小寫(xiě)
開(kāi)啟url模式時(shí)全部轉(zhuǎn)換為小寫(xiě):
if ($mode == 'url') {
$REQUEST = unserialize(strtolower(serialize($_REQUEST)));
}
權(quán)限校驗(yàn)核心代碼段之一,即循環(huán)所有該用戶(hù)權(quán)限 判斷 當(dāng)前需要驗(yàn)證的權(quán)限 是否 在用戶(hù)授權(quán)列表中:
foreach ($authList as $auth) {
$query = preg_replace('/^.+\?/U', '', $auth);//獲取url參數(shù)
if ($mode == 'url' && $query != $auth) {
parse_str($query, $param); //獲取數(shù)組形式url參數(shù)
$intersect = array_intersect_assoc($REQUEST, $param);
$auth = preg_replace('/\?.*$/U', '', $auth);//獲取訪(fǎng)問(wèn)的url文件
if (in_array($auth, $name) && $intersect == $param) { //如果節(jié)點(diǎn)相符且url參數(shù)滿(mǎn)足
$list[] = $auth;
}
} else if (in_array($auth, $name)) {
$list[] = $auth;
}
}
in_array($auth, $name) 如果 權(quán)限列表中 其中一條權(quán)限 等于 當(dāng)前需要校驗(yàn)的權(quán)限 則加入到$list中
注:
$list = array(); //保存驗(yàn)證通過(guò)的規(guī)則名
if ($relation == 'or' and !empty($list)) {
return true;
}
$diff = array_diff($name, $list);
if ($relation == 'and' and empty($diff)) {
return true;
}
$relation == 'or' and !empty($list); //當(dāng)or時(shí) 只要有一條是通過(guò)的 則 權(quán)限為真
$relation == 'and' and empty($diff); //當(dāng)and時(shí) $name與$list完全相等時(shí) 權(quán)限為真
3、獲取權(quán)限列表:
$authList = $this->getAuthList($uid, $type); //獲取用戶(hù)需要驗(yàn)證的所有有效規(guī)則列表
這個(gè)主要流程:
獲取用戶(hù)組
$groups = $this->getGroups($uid); //SELECT `rules` FROM think_auth_group_access a INNER JOIN think_auth_group g on a.group_id=g.id WHERE ( a.uid='1' and g.status='1' )
簡(jiǎn)化操作就是:
SELECT `rules` FROM think_auth_group WHERE STATUS = '1' AND id='1'//按正常流程 去think_auth_group_access表中內(nèi)聯(lián)有點(diǎn)多余....!
取得用戶(hù)組rules規(guī)則字段 這個(gè)字段中保存的是think_auth_rule規(guī)則表的id用,分割
$ids就是$groups變量最終轉(zhuǎn)換成的 id數(shù)組:
$map = array(
'id' => array('in', $ids),
'type' => $type,
'status' => 1,
);
取得think_auth_rule表中的規(guī)則信息,之后循環(huán):
foreach ($rules as $rule) {
if (!empty($rule['condition'])) { //根據(jù)condition進(jìn)行驗(yàn)證
$user = $this->getUserInfo($uid); //獲取用戶(hù)信息,一維數(shù)組
$command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $rule['condition']);
//dump($command);//debug
@(eval('$condition=(' . $command . ');'));
if ($condition) {
$authList[] = strtolower($rule['name']);
}
} else {
//只要存在就記錄
$authList[] = strtolower($rule['name']);
}
}
if (!empty($rule['condition'])) { //根據(jù)condition進(jìn)行驗(yàn)證
這里就可以明白getUserInfo 會(huì)去獲取配置文件AUTH_USER對(duì)應(yīng)表名 去查找用戶(hù)信息
重點(diǎn)是:
$command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $rule['condition']);
@(eval('$condition=(' . $command . ');'));
'/\{(\w*?)\}/ 可以看成要匹配的文字為 {字符串} 那么 {字符串} 會(huì)替換成$user['字符串']
$command =$user['字符串']
如果
$rule['condition'] = '{age}';
$command =$user['age']
$rule['condition'] = '{age} > 5';
$command =$user['age'] > 10
@(eval('$condition=(' . $command . ');'));
即:
$condition=($user['age'] > 10);
這時(shí)再看下面代碼 如果為真則加為授權(quán)列表
if ($condition) {
$authList[] = strtolower($rule['name']);
}
更多關(guān)于thinkPHP相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《ThinkPHP入門(mén)教程》、《thinkPHP模板操作技巧總結(jié)》、《ThinkPHP常用方法總結(jié)》、《smarty模板入門(mén)基礎(chǔ)教程》及《PHP模板技術(shù)總結(jié)》。
希望本文所述對(duì)大家基于ThinkPHP框架的PHP程序設(shè)計(jì)有所幫助。
- thinkPHP5框架auth權(quán)限控制類(lèi)與用法示例
- ThinkPHP菜單無(wú)極分類(lèi)實(shí)例講解
- Thinkphp自定義美化success和error提示跳轉(zhuǎn)頁(yè)面代碼實(shí)例
- thinkphp5.1的model模型自動(dòng)更新update_time字段實(shí)例講解
- Thinkphp5.1獲取項(xiàng)目根目錄以及子目錄路徑的方法實(shí)例講解
- Thinkphp使用Zxing擴(kuò)展庫(kù)解析二維碼內(nèi)容圖文講解
- ThinkPHP的標(biāo)簽制作實(shí)例講解
- thinkphp的鉤子的兩種配置和兩種調(diào)用方法
- 詳解thinkphp的Auth類(lèi)認(rèn)證
相關(guān)文章
PHP編實(shí)現(xiàn)程動(dòng)態(tài)圖像的創(chuàng)建代碼
只要安裝一些第三方的庫(kù)文件并具有一定的幾何知識(shí),就可以利用PHP來(lái)創(chuàng)建和處理圖像了。利用PHP創(chuàng)建動(dòng)態(tài)圖像是相當(dāng)容易的一件事情。下面,筆者將詳細(xì)介紹如何實(shí)現(xiàn)。2008-09-09
php使用phpoffice/phpspreadsheet拓展操作excel實(shí)例
這篇文章主要為大家介紹了php使用phpoffice/phpspreadsheet拓展操作excel實(shí)例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11
Linux下手動(dòng)編譯安裝PHP擴(kuò)展的例子分享
這篇文章主要介紹了Linux下手動(dòng)編譯安裝PHP擴(kuò)展的例子分享,本文以PDO_MYSQL為例,講解手動(dòng)編譯安裝PHP擴(kuò)展的方法,需要的朋友可以參考下2014-07-07
PHP Cli 模式設(shè)置進(jìn)程名稱(chēng)的方法
這篇文章主要介紹了PHP Cli 模式設(shè)置進(jìn)程名稱(chēng)的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-06-06
基于PHP技術(shù)開(kāi)發(fā)客服工單系統(tǒng)
這篇文章主要介紹了基于PHP技術(shù)開(kāi)發(fā)客服工單系統(tǒng),需要的朋友可以參考下2016-01-01
ThinkPHP框架實(shí)現(xiàn)的郵箱激活功能示例
這篇文章主要介紹了ThinkPHP框架實(shí)現(xiàn)的郵箱激活功能,結(jié)合實(shí)例形式分析了thinkPHP使用class.smtp.php及class.phpmailer.php類(lèi)文件進(jìn)行郵件發(fā)送實(shí)現(xiàn)激活功能的具體操作技巧,需要的朋友可以參考下2018-06-06

