## 应用最小权限原则
仅授予所需的最低权限。永远不要在应用程序查询中使用超级用户。
**错误(权限过于宽泛):**
sql
-- 应用程序使用超级用户连接
-- 或者授予应用程序角色所有权限
grant all privileges on all tables in schema public to app_user;
grant all privileges on all sequences in schema public to app_user;
-- 任何 SQL 注入都会变成灾难性的
-- drop table users; 会级联删除所有内容
**正确(最小化、具体的授权):**
sql
-- 创建没有默认权限的角色
create role app_readonly nologin;
-- 仅在特定表上授予 SELECT 权限
grant usage on schema public to app_readonly;
grant select on public.products, public.categories to app_readonly;
-- 创建具有有限范围的写入角色
create role app_writer nologin;
grant usage on schema public to app_writer;
grant select, insert, update on public.orders to app_writer;
grant usage on sequence orders_id_seq to app_writer;
-- 没有 DELETE 权限
-- 登录角色继承这些权限
create role app_user login password 'xxx';
grant app_writer to app_user;
撤销公共默认权限:
sql
-- 撤销默认的公共访问权限
revoke all on schema public from public;
revoke all on all tables in schema public from public;
参考:[Roles and Privileges](https://supabase.com/blog/postgres-roles-and-privileges)
数据来源:claude-code-templates(MIT),中文翻译由 AI 生成。详见关于我们。