composer require wenhainan/thinkphp6-auth安装Jump拓展
composer require liliuwei/thinkphp-jump创建权限检查中间件
php think make:middleware CheckAuth配置中间件别名 在需要验证权限的控制器类中调用该中间件
protected $middleware = ['auth'];Auth配置文件 权限处理中间件
checkAuth();
return $next($request);
}
function checkAuth() {
//已登录用户id
$id=session('id');
if (!$id) {
$this->redirect('/admin/login');
}
$module = request()->root(); //应用名
$controller = request()->controller(); //控制器名
$action = request()->action(); //方法名
// 请求到的规则名 AuthRule Name
$url=$module . '/' . $controller . '/' . $action;
//实例化Auth
$auth = new Auth();
if (!$auth->check( $url , $id ) ) {
// 没有权限跳转到未授权页面
$this->success("当前用户没有该操作权限,请联系管理员!",'../');
}
}
}
注意细节,冗余代码不必再用。
我的测试通过截图如下
测试用户登录
管理员登录
访问一个不存在控制器时,跳转到上一页
需要注意:
$url的值不在搜索的$not_check数组中,输出===》不存在
取反,输出===》存在
function create(){
echo "admin create ";
$url='/admin/Index/json';
// 排除权限
$not_check = ['/admin/Login/logout','/admin/Login','/admin/Index/unauth'];
// $url要搜索的值 $not_check要搜索的数组
if (in_array( $url, $not_check )) {
echo "存在";
}else{
echo "不存在";
}
}
所以排除的$not_check数组中的规则毫无必要,auth查询不到的合法规则都可以默认访问,不合法的规则会被拒绝。另外就是TP框架的异常处理来配合Auth的使用,来达到更好的权限控制。



