跳到主要内容

角色与权限

PostgreSQL 使用角色管理数据库权限。CloudBase PostgreSQL 中,前端用户请求通常映射到 anonauthenticated 等角色,服务端和管理工具则使用数据库账号访问。

常见角色

角色说明
anon未登录用户访问数据库时使用的角色
authenticated已登录用户访问数据库时使用的角色
业务服务账号云函数、云托管或后端服务使用的数据库账号
管理账号DMC、运维和数据库管理使用的高权限账号

实际角色和账号以控制台展示为准。生产环境不建议在业务代码中使用管理账号。

授权基础

表权限通过 grant 授予,通过 revoke 回收。

grant usage on schema public to authenticated;
grant select, insert, update, delete on public.todos to authenticated;

revoke delete on public.todos from authenticated;

如果表中使用自增序列,还需要授予序列权限。

grant usage, select on all sequences in schema public to authenticated;

与 RLS 的关系

grant 决定角色是否具备操作表的基础权限,RLS 决定具备权限后能访问哪些行。两者需要同时满足。

grant select on public.todos to authenticated;

alter table public.todos enable row level security;

create policy "read own rows"
on public.todos
for select
to authenticated
using (user_id = (select auth.uid()));

如果只授予了表权限但没有配置 RLS,前端可能读到超出预期的数据。如果启用了 RLS 但没有授予表权限,请求仍会失败。

创建业务服务账号

服务端建议使用独立账号,按业务范围授权。

create role app_server login password 'change-me';

grant usage on schema public to app_server;
grant select, insert, update on public.orders to app_server;
grant select on public.users to app_server;

密码应在控制台或密钥系统中管理。示例中的密码仅用于说明,不应直接用于生产环境。

权限排查

可以查询表权限和角色信息:

select grantee, privilege_type
from information_schema.role_table_grants
where table_schema = 'public'
and table_name = 'todos';

如果请求返回空数据但没有报错,通常需要检查 RLS 策略。如果返回 permission denied,则优先检查 schema、表、序列或函数授权。

更多排查路径请参考 权限与 RLS 问题