赞
踩
使用PG时经常有一类需求,某一个数据库的所有表都需要给某一个用户读权限,不管是已经创建的还是没有创建的。下面我们看下如何实现。
只读用户read_user
读写用户update_user
测试库ptest
create user update_user createdb;
create user read_user;
读写用户创建数据库
postgres=# \c - update_user
postgres=> create database ptest;
CREATE DATABASE
创建测试表
postgres=> \c ptest
You are now connected to database "ptest" as user "update_user".
ptest=> create table tbl1(i int);
CREATE TABLE
ptest=> create table tbl12(i int);
CREATE TABLE
3.1 只读用户查询无权限
ptest=> select * from tbl1;
ERROR: permission denied for relation tbl1
ptest=> select * from tbl12;
ERROR: permission denied for relation tbl12
(二选一)3.2 对现存表授权(单表)
ptest=> \c - update_user
You are now connected to database "ptest" as user "update_user".
ptest=> grant select on table tbl1 to read_user;
GRANT
(二选一)3.2 对现存表授权(批量)
ptest=> \c - update_user
You are now connected to database "ptest" as user "update_user".
ptest=> grant select on all tables in schema public to read_user;
GRANT
3.3 只读用户查询成功
ptest=> \c - read_user
You are now connected to database "ptest" as user "read_user".
ptest=> select * from tbl1;
i
---
(0 rows)
使用默认授权
注意:一定要使用普通用户执行,也就是创建表的用户,不要用超级用户执行,否则会默认赋给用户全部读写权限,即使你只是指定了SELECT权限!!
update_user默认授权给read_user
ptest=> \c - update_user
You are now connected to database "ptest" as user "update_user".
ptest=> ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO read_user;
ALTER DEFAULT PRIVILEGES
检查权限(这里的owner不能是超级用户,否则权限会没有限制,read_user也能写)
ptest=> \c - update_user
You are now connected to database "ptest" as user "update_user".
ptest=> \ddp
Default access privileges
Owner | Schema | Type | Access privileges
-------------+--------+-------+-------------------------
update_user | public | table | read_user=r/update_user
(1 row)
测试,没有显示授权,read_user也可以读表,无法写入。
ptest=> \c - update_user
You are now connected to database "ptest" as user "update_user".
ptest=> create table tblx(i int);
CREATE TABLE
ptest=> \c - read_user
You are now connected to database "ptest" as user "read_user".
ptest=> select * from tblx;
i
---
(0 rows)
ptest=> insert into tblx values (1);
ERROR: permission denied for relation tblx
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。