授权与收回
- sql中使用grant和revoke语句向用户授予或收回对数据的操作权限。
1.1 授权(grant)
语法: grant 权限 on 数据的(库、表、列)to 用户 【with grant option】。
使用者:数据库管理员(DBA)或者数据库的创建者或已经拥有该权限的用户都可以使用grant语句。
“关于【with grant option】”如果授权语法中含有【with grant option】,则获得某种权限的用户还可以把获得的权限再授予其他用户,否则不能把获得的权限给其他用户;具有【with grant option】的用户可以给它的子用户授权,但是子用户不能授权给父用户,或者祖先用户。也就是授权不能循环。
用途 | sql |
---|---|
授予user1查询student表的权限 | grant select on table student to user1 |
授予user1操作student表的所有权限,包括增删改查 | grant all privileges on table student to user1 |
授予所有用户查询student表的权限 | grant select on table student to public |
授予user1和user2对表student进行更新stuNo列(其他列不能修改),和查询的权限 | grant update(stuNo),select on table student to user1,user2 |
授予user1对表student insert的权限,并且允许用户将此权限再授予其他用户 | grant insert on table student to user1 whth grant option-----》下一条 |
由user1 授予user2 对表student的insert操作权限 | grant insert on table student to user2 whth grant option ------》下一条 |
由user2 授予user3 对表student的insert操作权限(由于没有with grant option 所以user3 无法再对其他用户授权对student表的insert操作) | grant insert on table student to user3 --------》end下一条 |
1.2 收回(revoke)
语法:revoke 权限 on 数据的(库、表、列)to 用户 【cascade|restrict】。
使用者:授予用户的权限可以由数据库管理员(DBA)或授权者使用revoke收回该用户的权限
关于【cascade|restrict】:
有这种情况:user1授权给user3对表student的select权限,user2也授予user3对表student的select权限,当user1收回user3对表student的select权限时,出现了问题,那就是此时是否对user2授予user3对表student的select权限???
所以出现了cascade和restrict
cascade 表示级联收回(强制性收回,不管其他用户是否授予了该用户权限),根据用户的链式授权进行链式收回权限;
restrict表示约束收回(但凡有一个其它用户授予了该用户的权限(相当于约束),那么就不能收回该用户的权限)。
数据库默认值不同有的是cascade,有的是restrict
用途 | sql |
---|---|
收回user1修改学生学号的权限 | revoke update(stuNo) on table student from user1 |
收回所有用户对表student的查询权限 | revoke select on table student from public |
把user11对表insert的权限收回(后面加了cascade,所以现在user1,user2,user3都失去了对表student进行insert的权限) | revoke insert on table student from user1 cascade |
注意:用户对自己创建的基本表和视图拥有全部操作权限,并且可以grant其它用户。
数据库角色
角色是权限的集合,在数据库中首先用create role 创建角色,然后用grant 给角色授权,用revoke收回角色的权限。
- 角色创建
create role 角色名(role1) - 给角色授权
grant 权限 on 数据的(库、表、列)to 角色 - 将一个角色授予其他的角色或者用户
grant 角色1,角色2, to ,角色3或用户 【with admin option】
该语句把角色授予用户,或者授予另一个角色。这样,一个角色(角色3)或者用户就拥有(角色1和角色2的所有权限的总和)。
【with admin option】:类似于【whth grant option】获得某种权限的角色或用户可以继续授权给其他角色。
一个角色的权限可以来自很多角色权限的总和。 - 角色权限的回收
revoke 权限 on 数据的(库、表、列)from 角色
用途 | sql |
---|---|
创建一个角色 | create role role1 |
赋予role1对表student的select update insert权限 | grant select,update,insert on table student to role1 |
将role1授予user1,user2,user3 | grant role1 to user1,user2,user3 |
通过role1 收回user2的权限 | revoke role1 from user2 |
角色权限修改(增加role1对表student的delete权限) | grant select on table student from role1 |
角色权限修改(删除role1对表student的update权限) | revoke update on table student from role1 |
视图机制了解
实例:辅导员有查询(select)班级信息的权限,院长有对班级信息所有的操作权限
- 创建视图:
create view CS_student as select * from student - 辅导员:
grant select on CS_student to fudaoyuan; - 院长:
grant all privileges on CS_student to yuanzhang;