ARTICLE · INTELLIGENCE

战地情报 · 详情页

来自尧图项目组的一线实战观察与深度解析

supabase-postgres-best-practices - security-rls-basics

supabase-postgres-best-practices - security-rls-basics

title: Enable Row Level Security for Multi-Tenant Data
impact: CRITICAL
impactDescription: Database-enforced tenant isolation, prevent data leaks
tags: rls, row-level-security, multi-tenant, security

多租户数据启用行级安全

行级安全(RLS)在数据库层面强制实施数据访问控制,确保用户只能看到自己的数据。

错误做法(仅依赖应用程序层过滤):

-- 仅依赖应用程序过滤select*fromorderswhereuser_id=$current_user_id;-- Bug 或绕过意味着所有数据都会暴露!select*fromorders;-- 返回所有订单

正确做法(数据库强制的 RLS):

-- 在表上启用 RLSaltertableordersenablerowlevelsecurity;-- 创建策略,使用户只能看到自己的订单createpolicy orders_user_policyonordersforallusing(user_id=current_setting('app.current_user_id')::bigint);-- 即使表所有者也要强制执行 RLSaltertableordersforcerowlevelsecurity;-- 设置用户上下文并查询setapp.current_user_id='123';select*fromorders;-- 只返回用户 123 的订单

面向 authenticated 角色的策略:

createpolicy orders_user_policyonordersforalltoauthenticatedusing(user_id=auth.uid());

参考:行级安全

RELATED READING

延伸阅读

更多一线实战笔记与深度复盘,助您持续精进