浅谈PostgreSQL用户权限
Posted lottu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了浅谈PostgreSQL用户权限相关的知识,希望对你有一定的参考价值。
盗用德哥的图;来诠释下逻辑结构;PostgreSQL逻辑结构有4层:实例->数据库->schema->数据库对象
可以看出用户不在PostgreSQL里面;是独立之外的object
# 创建用户lottu1 postgres=# create user lottu1; CREATE ROLE # 创建用户lottu2 postgres=# create user lottu2; CREATE ROLE # 创建数据库db1;属于lottu1 postgres=# create database db1 owner lottu1; CREATE DATABASE # 创建schema、table、并插入记录 postgres=# \\c db1 lottu1; You are now connected to database "db1" as user "lottu1". db1=> create schema lottu1; CREATE SCHEMA db1=> create table tbl_lottu_01(id int, info text, reg_time timestamp); CREATE TABLE db1=> insert into tbl_lottu_01 select 1,\'lottu\',now(); INSERT 0 1
新建的数据库对所有的用户都有连接权限;且数据库下public-schema对所有用户都可以使用;不管是不是超级用户、属主用户
db1=> \\c db1 lottu2 You are now connected to database "db1" as user "lottu2".
针对这种情况;这样是不是很不安全;非主用户为啥可以连数据库;非主用户为啥不及可以连数据库;还可以在对应的public-schema下可以创建object。要实现隔离;我们可以回收数据库权限;只有超级用户、属主用户可以连。
db1=> \\c db1 postgres You are now connected to database "db1" as user "postgres". db1=# revoke CONNECT ON DATABASE db1 from public; REVOKE db1=# \\c db1 postgres You are now connected to database "db1" as user "postgres". db1=# \\c db1 lottu1; You are now connected to database "db1" as user "lottu1". db1=> \\c db1 lottu2; FATAL: permission denied for database "db1" DETAIL: User does not have CONNECT privilege. Previous connection kept
现在实现用户lottu2不能连接数据库db1。现在需求tbl_lottu_01给db2查询。而表tbl_lottu_01属于数据库db1下面schema-lottu1的。
db1=> grant CONNECT ON DATABASE db1 to lottu2; GRANT db1=> grant USAGE ON SCHEMA lottu1 to lottu2; GRANT db1=> grant select on TABLE tbl_lottu_01 to lottu2; GRANT db1=> \\c db1 lottu2; You are now connected to database "db1" as user "lottu2". db1=> select * from lottu1.tbl_lottu_01; id | info | reg_time ----+-------+---------------------------- 1 | lottu | 2020-05-19 10:50:15.206569 (1 row)
经过一层层的赋权;用户lottu2可以select表tbl_lottu_01。若需求将schema-lottu1下所有的表都赋于给lottu2。将上面的修改下即可
grant select on ALL TABLES IN SCHEMA lottu1 to lottu2;
以上是关于浅谈PostgreSQL用户权限的主要内容,如果未能解决你的问题,请参考以下文章