跳到主要内容

角色与权限

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

常见角色

角色说明
anon未登录用户访问数据库时使用的角色
authenticated已登录用户访问数据库时使用的角色
service_role服务端管理场景使用的高权限角色,具备绕过 RLS 的能力
业务服务账号云函数、云托管或后端服务使用的数据库账号
管理账号DMC、运维和数据库管理使用的高权限账号

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

注意

service_role 可绕过 RLS 策略,只能用于云函数、云托管、后端服务或受控运维环境。不要将 service_role 对应密钥、连接信息或管理账号暴露在 Web、小程序、App 等客户端代码中。

未登录与已登录角色

未登录请求通常以 anon 角色访问数据库,登录后的用户请求通常以 authenticated 角色访问数据库。RLS Policy 的 TO 子句会限定策略适用的角色。

如果一条数据需要"所有人可读",通常需要同时写入 TO anon, authenticated,否则只允许 anon 可能导致登录用户无法命中该策略;只允许 authenticated 则未登录用户无法访问。

create policy "public read"
on public.articles
for select
to anon, authenticated
using (published = true);

授权基础

表权限通过 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 但没有授予表权限,请求仍会失败。对于 anon / authenticated 这类前端角色,建议先设计 RLS,再按最小权限授予表、序列和函数权限。

service_role 具备绕过 RLS 的能力,通常不需要为它单独编写 Policy;但仍应只在服务端受控逻辑中使用,并限制其可执行的业务入口。

创建业务服务账号

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

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 问题