Houze 文档 / 扩展组件 / Auth

扩展组件

Auth

houze\Auth 是基于 Redis 的角色权限(RBAC):用户挂角色,角色挂权限,判断「某人有没有某项权限」。数据存 Redis,不建表。

基本概念

用户 ──多个──▶ 角色 ──多个──▶ 权限
user:3        admin           article.delete

常用方法

方法作用
addRoleForUser($user, $role)给用户加角色
delRoleForUser($user, $role)移除角色
clearRoleForUser($user)清空该用户所有角色
getRoleForUser($user)查用户有哪些角色
getUserForRole($role)查某角色下有哪些用户
isRoleForUser($user, $role)判断用户是否属于某角色
delUser / delRole / delAuth删除用户 / 角色 / 权限

用法

$auth = new \houze\Auth();

// 授权
$auth->addRoleForUser('3', 'editor');

// 判断
if (!$auth->isRoleForUser('3', 'editor')) {
    return $this->api(403, '没有权限');
}

放在中间件里

class Admin extends \houze\Middleware
{
    public function handle()
    {
        $user = \houze\Session::get('admin');
        if (!$user) return $this->error('请先登录');

        $auth = new \houze\Auth();
        if (!$auth->isRoleForUser((string)$user['id'], 'admin')) {
            return $this->error('需要管理员权限');
        }
        return true;
    }
}

注意

  • 数据在 Redis,清库即清权限,重要环境要备份;
  • 用户标识统一用字符串,传 int 可能因为序列化差异查不到;
  • 它只管「角色归属」,具体的权限点校验还要自己写一层。

最后更新:2026-12-02 · 本文档对应 Houze v2.5.9,如有出入以框架源码为准。