自定义角色
Learn about using custom roles with storage schema
在本指南中,你将学习如何创建和使用带有 Storage 的自定义角色,以管理对对象和存储桶的基于角色的访问。同样的方法也可以用于在任何其他 Supabase 服务中使用自定义角色。
🌐 In this guide, you will learn how to create and use custom roles with Storage to manage role-based access to objects and buckets. The same approach can be used to use custom roles with any other Supabase service.
Supabase Storage 使用和其他任何使用 RLS(行级安全)的 Supabase 服务相同的基于角色的访问控制系统。
🌐 Supabase Storage uses the same role-based access control system as any other Supabase service using RLS (Row Level Security).
创建自定义角色 #
🌐 Create a custom role
创建一个自定义角色 manager,以提供对特定存储桶的完整读取访问权限。想要更高级的设置,请参阅 RBAC 指南。
🌐 Create a custom role manager to provide full read access to a specific bucket. For a more advanced setup, see the RBAC Guide.
1create role 'manager';23-- Important to grant the role to the authenticator and anon role4grant manager to authenticator;5grant anon to manager;创建一个政策 #
🌐 Create a policy
创建一个策略,为 manager 角色提供对桶 teams 中所有对象的完全读取权限。
🌐 Create a policy that gives full read permissions to all objects in the bucket teams for the manager role.
1create policy "Manager can view all files in the bucket 'teams'"2on storage.objects3for select4to manager5using (6 bucket_id = 'teams'7);测试政策 #
🌐 Test the policy
要扮演 manager 角色,你需要一个带有 manager 角色的有效 JWT 令牌。你可以使用 Node.js 里的 jsonwebtoken 库来创建一个。
🌐 To impersonate the manager role, you will need a valid JWT token with the manager role.
You can create one using the jsonwebtoken library in Node.js.
签发新的 JWT 需要你的 JWT_SECRET。你必须安全地存储这个密钥。切勿在前端代码中暴露它,也不要将其提交到版本控制中。
🌐 Signing a new JWT requires your JWT_SECRET. You must store this secret securely. Never expose it in frontend code, and do not check it into version control.
1const jwt = require('jsonwebtoken')23const JWT_SECRET = 'your-jwt-secret' // You can find this in your Supabase project settings under API. Store this securely.4const USER_ID = '' // the user id that we want to give the manager role56const token = jwt.sign({ role: 'manager', sub: USER_ID }, JWT_SECRET, {7 expiresIn: '1h',8})现在你可以用这个令牌访问存储 API 了。
🌐 Now you can use this token to access the Storage API.
1const { StorageClient } = require('@supabase/storage-js')23const PROJECT_URL = 'https://your-project-id.supabase.co/storage/v1'45const storage = new StorageClient(PROJECT_URL, {6 authorization: `Bearer ${token}`,7})89await storage.from('teams').list()