Skip to content
Storage

自定义角色

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.

1
create role 'manager';
2
3
-- Important to grant the role to the authenticator and anon role
4
grant manager to authenticator;
5
grant 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.

1
create policy "Manager can view all files in the bucket 'teams'"
2
on storage.objects
3
for select
4
to manager
5
using (
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.

1
const jwt = require('jsonwebtoken')
2
3
const JWT_SECRET = 'your-jwt-secret' // You can find this in your Supabase project settings under API. Store this securely.
4
const USER_ID = '' // the user id that we want to give the manager role
5
6
const 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.

1
const { StorageClient } = require('@supabase/storage-js')
2
3
const PROJECT_URL = 'https://your-project-id.supabase.co/storage/v1'
4
5
const storage = new StorageClient(PROJECT_URL, {
6
authorization: `Bearer ${token}`,
7
})
8
9
await storage.from('teams').list()