ThinkPHP Auth权限认证概述
本文通过具体代码实例,详细拆解了ThinkPHP框架中Auth权限认证功能的运作机理与实施步骤。
涉及MySQL数据库相关的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='用户组表';
-- ----------------------------
-- 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 '用户id',
`group_id` mediumint(8) unsigned NOT NULL COMMENT '用户组id',
UNIQUE KEY `uid_group_id` (`uid`,`group_id`),
KEY `uid` (`uid`),
KEY `group_id` (`group_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='用户组明细表';
-- ----------------------------
-- 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 '规则唯一标识',
`title` char(20) NOT NULL DEFAULT '' COMMENT '规则中文名称',
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态:为1正常,为0禁用',
`type` char(80) NOT NULL,
`condition` char(100) NOT NULL DEFAULT '' COMMENT '规则表达式,为空表示存在就验证,不为空表示按照条件验证',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT='规则表';
-- ----------------------------
-- 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(
//'配置项'=>'配置值'
'DB_DSN' => '', // 数据库连接DSN 用于PDO方式
'DB_TYPE' => 'mysql', // 数据库类型
'DB_HOST' => 'localhost', // 服务器地址
'DB_NAME' => 'thinkphp', // 数据库名
'DB_USER' => 'root', // 用户名
'DB_PWD' => 'root', // 密码
'DB_PORT' => 3306, // 端口
'DB_PREFIX' => 'think_', // 数据库表前缀
'AUTH_CONFIG' => array(
'AUTH_ON' => true, //认证开关
'AUTH_TYPE' => 1, // 认证方式,1为时时认证;2为登录认证。
'AUTH_GROUP' => 'think_auth_group', //用户组数据表名
'AUTH_GROUP_ACCESS' => 'think_auth_group_access', //用户组明细表
'AUTH_RULE' => 'think_auth_rule', //权限规则表
'AUTH_USER' => 'think_user'//用户信息表
)
);
Home模块下IndexController.class.php控制器的部分代码:
<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
public function index() {
$Auth = new \Think\Auth();
//需要验证的规则列表,支持逗号分隔的权限规则或索引数组
$name = MODULE_NAME . '/' . ACTION_NAME;
//当前用户id
$uid = '1';
//分类
$type = MODULE_NAME;
//执行check的模式
$mode = 'url';
//'or' 表示满足任一条规则即通过验证;
//'and'则表示需满足所有规则才能通过验证
$relation = 'and';
if ($Auth->check($name, $uid, $type, $mode, $relation)) {
die('认证:成功');
} else {
die('认证:失败');
}
}
}
上述代码构成了基础的权限验证逻辑示例。
Auth类初始化与配置合并
接下来进行源码层面的阅读与分析:
1、权限检验类初始化配置信息:
$Auth = new \Think\Auth();
对象实例化时,程序会自动合并配置数据 系统会读取并合并Application\Common\Conf\config.php中的AUTH_CONFIG数组内容
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')) {
//可设置配置项 AUTH_CONFIG, 此配置项为数组。
$this->_config = array_merge($this->_config, C('AUTH_CONFIG'));
}
}
权限检查逻辑与规则匹配
2、执行权限检查:
check($name, $uid, $type = 1, $mode = 'url', $relation = 'or')
对该方法的大致逻辑进行分析
首先检测权限校验是否被禁用,若配置项AUTH_ON设为false,则跳过验证直接返回;否则继续执行后续的权限校验流程
if (!$this->_config['AUTH_ON']) {
return true;
}
获取到权限列表后,下文将展开详细介绍:
$authList = $this->getAuthList($uid, $type);
将当前需要验证的规则列表转换为数组格式:
if (is_string($name)) {
$name = strtolower($name);
if (strpos($name, ',') !== false) {
$name = explode(',', $name);
} else {
$name = array($name);
}
}
因此$name参数不区分大小写,最终均会被统一转换为小写形式
当启用url模式时,所有相关值均转换为小写:
if ($mode == 'url') {
$REQUEST = unserialize(strtolower(serialize($_REQUEST)));
}
这是权限校验的核心代码段之一,即遍历用户的所有权限,判断当前待验证的权限是否存在于用户的授权列表中:
foreach ($authList as $auth) {
$query = preg_replace('/^.+\?/U', '', $auth);//获取url参数
if ($mode == 'url' && $query != $auth) {
parse_str($query, $param); //获取数组形式url参数
$intersect = array_intersect_assoc($REQUEST, $param);
$auth = preg_replace('/\?.*$/U', '', $auth);//获取访问的url文件
if (in_array($auth, $name) && $intersect == $param) { //如果节点相符且url参数满足
$list[] = $auth;
}
} else if (in_array($auth, $name)) {
$list[] = $auth;
}
}
in_array($auth, $name) 用于检查权限列表中是否存在一条与当前需校验权限相等的记录,若存在则将其加入$list集合中 注意:
$list = array(); //保存验证通过的规则名
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); //当or时 只要有一条是通过的 则 权限为真
$relation == 'and' and empty($diff); //当and时 $name与$list完全相等时 权限为真
获取用户权限列表流程
3、获取权限列表的过程:
$authList = $this->getAuthList($uid, $type); //获取用户需要验证的所有有效规则列表
主要执行流程如下:
获取用户所属的用户组信息
$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' )
简化后的操作逻辑为:
SELECT `rules` FROM think_auth_group WHERE STATUS = '1' AND id='1'//按正常流程 去think_auth_group_access表中内联有点多余....!
提取用户组的rules规则字段,该字段存储的是think_auth_rule规则表中对应规则的id,多个id之间以逗号分隔
$ids变量即为$groups变量最终转换生成的id数组:
$map = array(
'id' => array('in', $ids),
'type' => $type,
'status' => 1,
);
从think_auth_rule表中获取规则详细信息,随后进行循环处理:
foreach ($rules as $rule) {
if (!empty($rule['condition'])) { //根据condition进行验证
$user = $this->getUserInfo($uid); //获取用户信息,一维数组
$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'])) { //根据condition进行验证
由此可知getUserInfo方法会依据配置文件AUTH_USER指定的表名来查询用户相关信息
关键点在于:
$command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $rule['condition']);
@(eval('$condition=(' . $command . ');'));
'/\{(\w*?)\}/ 正则表达式用于匹配形如 {字符串} 的内容,匹配到的 {字符串} 将被替换为$user['字符串']的值 $command =$user['字符串']
如果条件成立
$rule['condition'] = '{age}';
$command =$user['age']
$rule['condition'] = '{age} > 5';
$command =$user['age'] > 10
@(eval('$condition=(' . $command . ');'));
即:
$condition=($user['age'] > 10);
此时再审视下方代码,若条件为真,则将该规则加入授权列表
if ($condition) {
$authList[] = strtolower($rule['name']);
}
希望本文所述内容对基于ThinkPHP框架的PHP程序设计有所帮助。