惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
腾讯CDC
宝玉的分享
宝玉的分享
量子位
Recent Announcements
Recent Announcements
Martin Fowler
Martin Fowler
J
Java Code Geeks
V
Visual Studio Blog
阮一峰的网络日志
阮一峰的网络日志
Blog — PlanetScale
Blog — PlanetScale
大猫的无限游戏
大猫的无限游戏
博客园 - 叶小钗
S
SegmentFault 最新的问题
B
Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 【当耐特】
小众软件
小众软件
The Cloudflare Blog
Y
Y Combinator Blog
I
InfoQ
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
GbyAI
GbyAI
IT之家
IT之家

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Supabase RLS Deep Dive — Multi-tenant Access Control
kanta13jp1 · 2026-04-29 · via DEV Community

kanta13jp1

Supabase RLS Deep Dive — Multi-tenant Access Control

Supabase Row Level Security (RLS) lets you enforce access rules at the database layer using SQL policies. Done right, your app code never needs explicit permission checks. Here are the patterns I use in a multi-tenant SaaS.

The Basics

-- Enable RLS on a table
ALTER TABLE tasks ENABLE ROW LEVEL SECURITY;

-- Only the owner can see their own rows
CREATE POLICY "own_tasks_select"
  ON tasks FOR SELECT
  USING (user_id = auth.uid());

-- INSERT must set user_id to the caller
CREATE POLICY "own_tasks_insert"
  ON tasks FOR INSERT
  WITH CHECK (user_id = auth.uid());

Enter fullscreen mode Exit fullscreen mode

Multi-tenant: Organization-based Access

CREATE TABLE organizations (
  id   UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name TEXT NOT NULL,
  slug TEXT UNIQUE NOT NULL
);

CREATE TABLE organization_members (
  org_id  UUID REFERENCES organizations(id) ON DELETE CASCADE,
  user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
  role    TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'member')),
  PRIMARY KEY (org_id, user_id)
);

-- Helper: return the caller's org IDs
CREATE OR REPLACE FUNCTION my_org_ids()
RETURNS SETOF UUID LANGUAGE SQL STABLE SECURITY DEFINER AS $$
  SELECT org_id FROM organization_members WHERE user_id = auth.uid()
$$;

CREATE TABLE projects (
  id     UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  org_id UUID REFERENCES organizations(id) ON DELETE CASCADE,
  name   TEXT NOT NULL
);
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;

-- Read: any org member
CREATE POLICY "org_projects_select"
  ON projects FOR SELECT
  USING (org_id IN (SELECT my_org_ids()));

-- Write: admin or owner only
CREATE POLICY "org_projects_write"
  ON projects FOR INSERT
  WITH CHECK (
    EXISTS (
      SELECT 1 FROM organization_members
      WHERE org_id = projects.org_id
        AND user_id = auth.uid()
        AND role IN ('owner', 'admin')
    )
  );

Enter fullscreen mode Exit fullscreen mode

Speed Up With JWT Custom Claims

Subquerying organization_members on every row is slow. Embed org_ids in the JWT instead.

-- Read from JWT app_metadata (no extra DB hit)
CREATE OR REPLACE FUNCTION auth_org_ids()
RETURNS SETOF UUID LANGUAGE SQL STABLE AS $$
  SELECT jsonb_array_elements_text(
    (auth.jwt() -> 'app_metadata' -> 'org_ids')
  )::UUID
$$;

CREATE POLICY "jwt_projects_select"
  ON projects FOR SELECT
  USING (org_id IN (SELECT auth_org_ids()));

Enter fullscreen mode Exit fullscreen mode

// Edge Function: refresh JWT claims after org membership changes
const { data: memberships } = await adminClient
  .from('organization_members')
  .select('org_id')
  .eq('user_id', userId);

await adminClient.auth.admin.updateUserById(userId, {
  app_metadata: { org_ids: memberships?.map(m => m.org_id) ?? [] }
});

Enter fullscreen mode Exit fullscreen mode

Public Read + Auth Write

CREATE TABLE posts (
  id        UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  author_id UUID REFERENCES auth.users(id),
  title     TEXT NOT NULL,
  published BOOLEAN DEFAULT false
);
ALTER TABLE posts ENABLE ROW LEVEL SECURITY;

-- Anyone can read published posts; authors see their own drafts
CREATE POLICY "posts_select"
  ON posts FOR SELECT
  USING (published = true OR author_id = auth.uid());

-- Only the author can write
CREATE POLICY "posts_write"
  ON posts FOR ALL
  USING (author_id = auth.uid())
  WITH CHECK (author_id = auth.uid());

Enter fullscreen mode Exit fullscreen mode

Service Role Bypasses RLS

// Full access — server-side only
const adminClient = createClient(url, serviceRoleKey);
// ⚠️ This ignores ALL RLS policies

// User-scoped requests — RLS is enforced
const userClient = createClient(url, anonKey, {
  global: { headers: { Authorization: `Bearer ${userJwt}` } }
});

Enter fullscreen mode Exit fullscreen mode

Performance Checklist

-- Always index the columns referenced in policies
CREATE INDEX ON tasks (user_id);
CREATE INDEX ON projects (org_id);
CREATE INDEX ON organization_members (user_id);

-- Verify your policy uses an index
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM projects WHERE org_id = '<org>';

Enter fullscreen mode Exit fullscreen mode

Summary

Pattern Use when
auth.uid() direct Personal data
Junction table + helper Multi-tenant org roles
JWT custom claims High-traffic tables (skip JOIN)
published flag Public/private content
Service Role Server-side admin operations

After implementing these patterns, our security audit concluded that zero app-layer permission checks were needed — the database enforces everything.


What RLS patterns have you used in production? Leave a comment!