Yii2 restful接口方式开发,权限控制(yii2-rest-rbac)
Posted windhoney
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Yii2 restful接口方式开发,权限控制(yii2-rest-rbac)相关的知识,希望对你有一定的参考价值。
根据yii2-admin(https://github.com/mdmsoft/yi...)修改,yii2-admin只是web方式,这个相当于yii2-admin的rest版本。适合用于前后端分离项目,rest方式提供接口,实现对接口的权限控制。
项目地址:https://github.com/windhoney/...
yii2-rest-rbac
Yii2权限系统,rest版,根据yii2-admin(https://github.com/mdmsoft/yii2-admin)修改
- 安装:
composer require windhoney/yii2-rest-rbac
使用
配置oauth2和rbac
‘modules‘ => [
‘rbac‘ => [
‘class‘ => ‘wind
estmodules‘
],
‘oauth2‘ => [
‘class‘ => ‘filshyii2oauth2serverModule‘,
‘tokenParamName‘ => ‘access_token‘,
‘tokenAccessLifetime‘ => 3600 * 24,
‘storageMap‘ => [
‘user_credentials‘ => ‘backendmodelsUser‘,
],
‘grantTypes‘ => [
‘user_credentials‘ => [
‘class‘ => ‘OAuth2GrantTypeUserCredentials‘,
],
‘client_credentials‘ => [
‘class‘ => ‘OAuth2GrantTypeClientCredentials‘,
],
‘refresh_token‘ => [
‘class‘ => ‘OAuth2GrantTypeRefreshToken‘,
‘always_issue_new_refresh_token‘ => true
],
‘authorization_code‘ => [
‘class‘ => ‘OAuth2GrantTypeAuthorizationCode‘
],
]
]
],
‘components‘ => [
‘authManager‘ => [
‘class‘ => ‘wind
estcomponentsDbManager‘, //配置文件
],
]
配置权限
‘as access‘ => [
‘class‘ => ‘wind
estcomponentsAccessControl‘,
‘allowActions‘ => [
‘site/*‘,//允许访问的节点,可自行添加
‘rbac/menu/user-menu‘,
‘oauth2/*‘,
]
],
创建所需要的表
1. 用户表user和菜单表menu
yii migrate [email protected]/windhoney/yii2-rest-rbac/migrations
2. rbac相关权限表
yii migrate [email protected]/rbac/migrations/
auth_item
表添加一个字段parent_name
varchar(30) COLLATE utf8_unicode_ci DEFAULT ‘‘ COMMENT ‘父级名称‘,3. oauth2相关表
yii migrate [email protected]/filsh/yii2-oauth2-server/migrations
4. 新增分组表
CREATE TABLE `auth_groups` (
`group_id` varchar(50) NOT NULL COMMENT ‘分组id‘,
`group_name` varchar(100) NOT NULL DEFAULT ‘‘ COMMENT ‘分组名称‘,
`group_status` varchar(50) NOT NULL DEFAULT ‘‘ COMMENT ‘状态(开启,关闭)‘,
PRIMARY KEY (`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=‘分组‘;
CREATE TABLE `auth_groups_child` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`group_id` varchar(50) NOT NULL COMMENT ‘分组id‘,
`user_id` varchar(64) NOT NULL COMMENT ‘用户id‘,
PRIMARY KEY (`id`),
UNIQUE KEY `group_id_2` (`group_id`,`user_id`),
KEY `group_id` (`group_id`),
KEY `user_group_id` (`user_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=795 DEFAULT CHARSET=utf8 COMMENT=‘分组子集‘;
添加路由配置
- 将yii2-rest-rbac/example/rbac_route.php文件内容配置到项目的urlManager的rules规则下
- 或者在main.php文件中 添加
$dir = __DIR__ . "/route";
$main = wind
esthelperRbacHelper::addRoute($dir, $main);
return $main;
并将此文件放到config/route/rbac_route.php
接口文档参考
以上是关于Yii2 restful接口方式开发,权限控制(yii2-rest-rbac)的主要内容,如果未能解决你的问题,请参考以下文章