ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user
1 | GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly; |
readonly用户可以连接,查看表,但是当它尝试进行简单的选择时,它会获得:
1 2 | ERROR: permission denied FOR relation mytable SQL state: 42501 |
这发生在PostgreSQL 9.1上
我做错了什么?
这是最近更新的PostgreSQL 9+的完整解决方案。
1 2 3 4 5 6 7 8 9 10 11 12 | CREATE USER readonly WITH ENCRYPTED PASSWORD 'readonly'; GRANT USAGE ON SCHEMA public TO readonly; ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly; -- repeat code below for each database: GRANT CONNECT ON DATABASE foo TO readonly; \c foo ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO readonly; --- this grants privileges on new tables generated in new database"foo" GRANT USAGE ON SCHEMA public TO readonly; GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO readonly; GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly; |
感谢https://jamie.curle.io/creating-a-read-only-user-in-postgres/的几个重要方面
如果有人找到更短的代码,并且最好是能够为所有现有数据库执行此操作的代码,则需要额外的荣誉。
尝试添加
1 | GRANT USAGE ON SCHEMA public TO readonly; |
您可能不知道需要拥有模式的必需权限才能使用模式中的对象。
确保您的用户具有其角色的属性。例如:
1 2 3 4 5 6 | postgres=# \du List OF roles ROLE name | Attributes | Member OF -----------+------------------------------------------------+----------- flux | | {} postgres | Superuser, CREATE ROLE, CREATE DB, Replication | {} |
执行以下命令后:
1 2 3 4 5 6 7 8 | postgres=# ALTER ROLE flux WITH Superuser; ALTER ROLE postgres=# \du List OF roles ROLE name | Attributes | Member OF -----------+------------------------------------------------+----------- flux | Superuser | {} postgres | Superuser, CREATE ROLE, CREATE DB, Replication | {} |
它解决了这个问题。
请参阅此处的角色和内容教程:https://www.digitalocean.com/community/tutorials/how-to-use-roles-and-manage-grant-permissions-in-postgresql-on-a-vps--2
这对我有用:
使用以下命令检查您登录的当前角色:
SELECT CURRENT_USER,SESSION_USER;
注意:它必须与架构的所有者匹配。
架构|名称|输入|所有者
-------- + -------- + ------- + ----------
如果所有者不同,则通过以下方式将所有授权从admin角色授予当前用户角色:
授予'ROLE_OWNER'到'CURRENT ROLENAME';
然后尝试执行查询,它将给出输出,因为它现在可以访问所有关系。
您应该执行下一个查询:
1 | GRANT ALL ON TABLE mytable TO myuser; |
或者,如果您的错误在视图中,那么表可能没有权限,因此您应该执行下一个查询:
1 | GRANT ALL ON TABLE tbm_grupo TO myuser; |