應用場景:
程式需要同時連接配接放在一台伺服器裡的兩個資料庫,其中一個資料庫db2裡存放機密資料,不希望被使用者通路到。兩個資料庫和表的owner都是postgres,為superuser。是以希望使用者無法登入資料庫db2,但不影響對資料庫db1和其中的表進行所有權限的操作。
簡化問題:如何使使用者user1隻對指定資料庫db1中的表進行操作,而沒有權限登入其他資料庫db2。
解決思路:建立使用者user1,将資料庫db1的owner指定為使用者user1,對資料庫db1内所有表賦予使用者user1所有權限。同時由于另一個資料庫db2的owner為postgres,user1沒有權限登入db2。
pg庫中使用者權限分為兩種:對資料庫操作的權限,對表操作的權限。
一、資料庫權限的設定需要進入到psql中
1. 賦予權限需要以管理者賬号登入進行修改。
psql -U postgres
2. 建立使用者user1,設定密碼。例如123456(需加單引号)。
create user user1 with password '123456';
3. 修改資料庫owner
alter database db1 owner to user1;
4. 賦予使用者user1操作資料庫的權限
grant all privileges on database db1 to user1;
二、對某資料庫中表的權限進行設定需要進入到對應庫中。
例如想要對資料庫db1進行操作,将權限賦給使用者user1:
1. 進入管理者
psql -U postgres
2. 進入對應資料庫db1
\c db1
3. 賦予使用者user1資料庫操作權限
grant all privileges on all tables in schema public to user1;