Token Security and Row Level Security
When you enable OAuth 2.1 in your Supabase project, third-party applications can access user data on their behalf. Row Level Security (RLS) policies are crucial for controlling exactly what data each OAuth client can access.
Scopes control OIDC data, not database access
The OAuth scopes (openid, email, profile, phone) control what user information is included in ID tokens and returned by the UserInfo endpoint. They do not control access to your database tables or API endpoints.
Use RLS to define which OAuth clients can access which data, regardless of the scopes they requested.
How OAuth tokens work with RLS
OAuth access tokens issued by Supabase Auth are JWTs that include all standard Supabase claims plus OAuth-specific claims. This means your existing RLS policies continue to work, and you can add OAuth-specific logic to create granular access controls.
Token structure
Every OAuth access token includes:
1234567891011121314{ "sub": "user-uuid", "role": "authenticated", "aud": "authenticated", "user_id": "user-uuid", "email": "user@example.com", "client_id": "9a8b7c6d-5e4f-3a2b-1c0d-9e8f7a6b5c4d", "aal": "aal1", "amr": [{ "method": "password", "timestamp": 1735815600 }], "session_id": "session-uuid", "iss": "https://<project-ref>.supabase.co/auth/v1", "iat": 1735815600, "exp": 1735819200}The key OAuth-specific claim is:
| Claim | Description |
|---|---|
client_id | Unique identifier of the OAuth client that obtained this token |
You can use this claim in RLS policies to grant different permissions to different clients.
Extracting OAuth claims in RLS
Use the auth.jwt() function to access token claims in your policies:
12345678-- Get the client ID from the token(auth.jwt() ->> 'client_id')-- Check if the token is from an OAuth client(auth.jwt() ->> 'client_id') IS NOT NULL-- Check if the token is from a specific client(auth.jwt() ->> 'client_id') = 'mobile-app-client-id'Common RLS patterns for OAuth
Pattern 1: Grant specific client full access
Allow a specific OAuth client to access all user data:
123456CREATE POLICY "Mobile app can access user data"ON user_data FOR ALLUSING ( auth.uid() = user_id AND (auth.jwt() ->> 'client_id') = 'mobile-app-client-id');Pattern 2: Grant multiple clients read-only access
Allow several OAuth clients to read data, but not modify it:
12345678910CREATE POLICY "Third-party apps can read profiles"ON profiles FOR SELECTUSING ( auth.uid() = user_id AND (auth.jwt() ->> 'client_id') IN ( 'analytics-client-id', 'reporting-client-id', 'dashboard-client-id' ));Pattern 3: Restrict sensitive data from OAuth clients
Prevent OAuth clients from accessing sensitive data:
123456CREATE POLICY "OAuth clients cannot access payment info"ON payment_methods FOR ALLUSING ( auth.uid() = user_id AND (auth.jwt() ->> 'client_id') IS NULL -- Only direct user sessions);Pattern 4: Client-specific data access
Different clients access different subsets of data:
123456789101112131415-- Analytics client can only read aggregated dataCREATE POLICY "Analytics client reads summaries"ON user_metrics FOR SELECTUSING ( auth.uid() = user_id AND (auth.jwt() ->> 'client_id') = 'analytics-client-id');-- Admin client can read and modify all dataCREATE POLICY "Admin client full access"ON user_data FOR ALLUSING ( auth.uid() = user_id AND (auth.jwt() ->> 'client_id') = 'admin-client-id');Real-world examples
Example 1: Multi-platform application
You have a web app, mobile app, and third-party integrations:
123456789101112131415161718192021222324252627-- Web app: Full accessCREATE POLICY "Web app full access"ON profiles FOR ALLUSING ( auth.uid() = user_id AND ( (auth.jwt() ->> 'client_id') = 'web-app-client-id' OR (auth.jwt() ->> 'client_id') IS NULL -- Direct user sessions ));-- Mobile app: Read-only access to profilesCREATE POLICY "Mobile app reads profiles"ON profiles FOR SELECTUSING ( auth.uid() = user_id AND (auth.jwt() ->> 'client_id') = 'mobile-app-client-id');-- Third-party integration: Limited data accessCREATE POLICY "Integration reads public data"ON profiles FOR SELECTUSING ( auth.uid() = user_id AND (auth.jwt() ->> 'client_id') = 'integration-client-id' AND is_public = true);Custom access token hooks
Custom Access Token Hooks work with OAuth tokens, allowing you to inject custom claims based on the OAuth client. This is particularly useful for customizing standard JWT claims like audience (aud) or adding client-specific metadata.
Custom Access Token Hooks are triggered for all token issuance. Use client_id or authentication_method (oauth_provider/authorization_code for OAuth flows) to differentiate OAuth from regular authentication.
Customizing the audience claim
A common use case is customizing the audience claim for different OAuth clients. This allows third-party services to validate that tokens were issued specifically for them:
1234567891011121314151617181920212223242526272829303132333435import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'serve(async (req) => { const { user, claims, client_id } = await req.json() // Customize audience based on OAuth client if (client_id === 'mobile-app-client-id') { return new Response( JSON.stringify({ claims: { aud: 'https://api.myapp.com', app_version: '2.0.0', }, }), { headers: { 'Content-Type': 'application/json' } } ) } if (client_id === 'analytics-partner-id') { return new Response( JSON.stringify({ claims: { aud: 'https://analytics.partner.com', access_level: 'read-only', }, }), { headers: { 'Content-Type': 'application/json' } } ) } // Default audience for non-OAuth flows return new Response(JSON.stringify({ claims: {} }), { headers: { 'Content-Type': 'application/json' }, })})The audience claim is especially important for:
- JWT validation by third parties: Services can verify tokens were issued for their specific API
- Multi-tenant applications: Different audiences for different client applications
- Compliance: Meeting security requirements that mandate audience validation
Adding client-specific claims
You can also add custom claims and metadata based on the OAuth client:
12345678910111213141516171819202122232425262728293031323334353637import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'serve(async (req) => { const { user, claims, client_id } = await req.json() const supabase = createClient(Deno.env.get('SUPABASE_URL')!, Deno.env.get('SUPABASE_SECRET_KEY')!) // Add custom claims based on OAuth client let customClaims = {} if (client_id === 'mobile-app-client-id') { customClaims.aud = 'https://mobile.myapp.com' customClaims.app_version = '2.0.0' customClaims.platform = 'mobile' } else if (client_id === 'analytics-client-id') { customClaims.aud = 'https://analytics.myapp.com' customClaims.read_only = true customClaims.data_retention_days = 90 } else if (client_id?.startsWith('mcp-')) { // MCP AI agents const { data: agent } = await supabase .from('approved_ai_agents') .select('name, max_data_retention_days') .eq('client_id', client_id) .single() customClaims.aud = `https://mcp.myapp.com/${client_id}` customClaims.ai_agent = true customClaims.agent_name = agent?.name customClaims.max_retention = agent?.max_data_retention_days } return new Response(JSON.stringify({ claims: customClaims }), { headers: { 'Content-Type': 'application/json' }, })})Use these custom claims in RLS:
123456789101112131415161718-- Policy based on custom claimsCREATE POLICY "Read-only clients cannot modify"ON user_data FOR UPDATEUSING ( auth.uid() = user_id AND (auth.jwt() -> 'user_metadata' ->> 'read_only')::boolean IS NOT TRUE);-- Policy based on audience claimCREATE POLICY "Only specific audience can access"ON api_data FOR SELECTUSING ( auth.uid() = user_id AND (auth.jwt() ->> 'aud') IN ( 'https://api.myapp.com', 'https://mobile.myapp.com' ));Security best practices
1. Principle of least privilege
Grant OAuth clients only the minimum permissions they need:
123456789101112-- Bad: Grant all access by defaultCREATE POLICY "OAuth clients full access"ON user_data FOR ALLUSING (auth.uid() = user_id);-- Good: Grant specific access per clientCREATE POLICY "Specific client specific access"ON user_data FOR SELECTUSING ( auth.uid() = user_id AND (auth.jwt() ->> 'client_id') = 'trusted-client-id');2. Separate policies for OAuth clients
Create dedicated policies for OAuth clients rather than mixing them with user policies:
123456789101112131415-- User accessCREATE POLICY "Users access their own data"ON user_data FOR ALLUSING ( auth.uid() = user_id AND (auth.jwt() ->> 'client_id') IS NULL);-- OAuth client access (separate policy)CREATE POLICY "OAuth clients limited access"ON user_data FOR SELECTUSING ( auth.uid() = user_id AND (auth.jwt() ->> 'client_id') IN ('client-1', 'client-2'));3. Regularly audit OAuth clients
Track and review which clients have access:
12345678910-- View all active OAuth clientsSELECT oc.client_id, oc.name, oc.created_at, COUNT(DISTINCT s.user_id) as active_usersFROM auth.oauth_clients ocLEFT JOIN auth.sessions s ON s.client_id = oc.client_idWHERE s.created_at > NOW() - INTERVAL '30 days'GROUP BY oc.client_id, oc.name, oc.created_at;Testing your policies
Always test your RLS policies before deploying to production:
123456789101112-- Test as a specific OAuth clientSET request.jwt.claims = '{ "sub": "test-user-uuid", "role": "authenticated", "client_id": "test-client-id"}';-- Test queriesSELECT * FROM user_data WHERE user_id = 'test-user-uuid';-- ResetRESET request.jwt.claims;Or use the Supabase Dashboard's RLS policy tester.
Troubleshooting
Policy not working for OAuth client
Problem: OAuth client can't access data despite having a valid token.
Check:
- Verify the policy includes the client's
client_id - Ensure RLS is enabled on the table
- Check for conflicting restrictive policies
- Test with service role key to isolate RLS issues
123456-- Debug: See what client_id is in the tokenSELECT auth.jwt() ->> 'client_id';-- Debug: Test without RLSSET LOCAL role = service_role;SELECT * FROM your_table;Policy too permissive
Problem: OAuth client has access to data it shouldn't.
Solution: Use AS RESTRICTIVE policies to add additional constraints:
12345678910-- This policy runs in addition to permissive policiesCREATE POLICY "Restrict OAuth clients"ON sensitive_dataAS RESTRICTIVEFOR ALLTO authenticatedUSING ( -- OAuth clients cannot access this table at all (auth.jwt() ->> 'client_id') IS NULL);Can't differentiate between users and OAuth clients
Problem: Need to apply different logic for direct user sessions vs OAuth.
Solution: Check if client_id is present:
123456789101112131415-- Direct user sessions (no OAuth)CREATE POLICY "Direct users full access"ON user_data FOR ALLUSING ( auth.uid() = user_id AND (auth.jwt() ->> 'client_id') IS NULL);-- OAuth clients (limited access)CREATE POLICY "OAuth clients read only"ON user_data FOR SELECTUSING ( auth.uid() = user_id AND (auth.jwt() ->> 'client_id') IS NOT NULL);Next steps
- Learn about JWTs - Deep dive into Supabase token structure
- Row Level Security - Complete RLS guide
- Custom Access Token Hooks - Inject custom claims
- OAuth flows - Understand token issuance