跳到主要内容

角色管理

一、创建角色

创建的角色,默认是未激活的.

-- host_name 默认为 % , 可以省略
create role 'role_name'@'host_name';

create role 'role1', 'role2'@'%';

二、给角色赋权

grant privileges on database_name.table_name to 'role_name'@'host_name';

-- 和给用户授权语法类似.
grant select,update on dbtest1.* to 'boss'@'%';

三、查看角色权限

show grants for 'boss';

四、回收角色权限

revoke update on dbtest1.* from 'boss'@'%';

五、删除角色

drop role 'boss';

六、给用户赋予角色

grant role_name to user_name;

grant 'boss' to 'user1'@'%';
grant 'boss'@'%' to 'user1'@'%';
show grants for 'user1'@'%';

七、激活角色

-- 1. set default role 
set default role 'boss'@'%' to 'user1'@'%';

-- 2. 将 active_all_roles_on_login 设置为 ON
show variables like 'activate_all_roles_on_login';
set global activate_all_roles_on_login=ON;
-- 查看当前会话的角色
SELECT CURRENT_ROLE();

八、撤销用户的角色

revoke 'boss' from 'user1'@'%';

九、设置强制角色(mandatory role)

所有用户默认有 mandatory 角色的权限.

-- 1. 服务启动前设置
mandatory_roles='role1,role2@localhost,r3@%.wangzhy.com'
-- 2. 运行时设置
-- 系统重启后,任然有效
set persist mandatory_roles= 'role1,role2@localhost,r3@%.wangzhy.com'
-- 系统重启后,失效
set global mandatory_riles= 'role1,role2@localhost,r3@%.wangzhy.com'