0Pricing
Supabase Backend as a Service · 课时

使用策略管理访问权限

使用 Supabase Storage 策略为文件实现细粒度的访问控制,确保数据安全。

使用策略管理访问权限 是 CoddyKit 上的免费 Supabase Backend as a Service 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Supabase Backend as a Service 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Supabase Backend as a Service 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Intro to Storage Policies

Welcome! In this lesson, we'll dive into Supabase Storage Policies. These policies are your key to controlling who can access, upload, or delete files in your buckets.

Think of them as security guards for your cloud files, ensuring only authorized actions happen.

Why Storage Security Matters

Without proper policies, your files could be vulnerable. Anyone could potentially upload malicious content, or sensitive user data might be publicly exposed.

  • Prevent unauthorized access: Keep private files secure.
  • Control uploads: Ensure only legitimate users can add files.
  • Manage deletions: Prevent accidental or malicious file removal.

Policies are essential for building secure applications.

Enabling RLS for Buckets

Just like with database tables, Supabase Storage uses Row-Level Security (RLS) for buckets. Before you can apply any policies, RLS must be enabled for your storage bucket.

You can do this in the Supabase dashboard under 'Storage' by clicking on a bucket and toggling 'Enable RLS', or directly with SQL:

ALTER TABLE storage.buckets
  ENABLE ROW LEVEL SECURITY;

Understanding Policy Syntax

Storage policies are written using SQL, similar to database RLS. They specify what actions are allowed (SELECT, INSERT, UPDATE, DELETE) and under what conditions.

Key parts of a policy:

  • CREATE POLICY: Starts the policy definition.
  • ON storage.objects: Specifies the table policies apply to.
  • FOR [action]: Defines the operation (SELECT, INSERT, UPDATE, DELETE).
  • USING / WITH CHECK: Sets the conditions for the policy.

Policy: Public Read Access

Let's create a policy to allow anyone to read files from a specific bucket, for example, a 'public-images' bucket. This is common for assets like profile pictures or product images.

The auth.role() = 'anon' part means unauthenticated users, and auth.role() = 'authenticated' means logged-in users. We'll allow both here.

CREATE POLICY "Allow public read access"
  ON storage.objects FOR SELECT
  TO public
  USING (bucket_id = 'public-images');

Policy: Authenticated User Uploads

Now, let's create a policy that allows only authenticated users to upload files to a 'user-uploads' bucket. Crucially, we want them to only upload into a folder named after their own user ID.

We use auth.uid() to get the current user's ID and path_tokens[1] to check the first part of the file path.

CREATE POLICY "Allow authenticated user upload"
  ON storage.objects FOR INSERT
  TO authenticated
  WITH CHECK (bucket_id = 'user-uploads' AND auth.uid()::text = path_tokens[1]);

Policy: Authenticated User Read Their Own

To complement the upload policy, let's ensure authenticated users can *only* read files that they themselves own within the 'user-uploads' bucket.

This policy uses auth.uid() to match the owner of the file (which is stored in the owner column of storage.objects) and also checks the file path.

CREATE POLICY "Allow authenticated user read their own"
  ON storage.objects FOR SELECT
  TO authenticated
  USING (bucket_id = 'user-uploads' AND auth.uid() = owner);

The storage.objects Table

Storage policies operate on the hidden storage.objects table. This table stores metadata about every file in your buckets. Understanding its columns is vital for writing effective policies.

  • id: Unique identifier for the object.
  • bucket_id: The ID of the bucket the object belongs to.
  • name: The full path and filename.
  • owner: The auth.uid() of the user who uploaded the file.
  • path_tokens: An array of strings representing the path segments.

Policy: Admin-Only Delete

Sometimes, only specific users (like administrators) should be able to delete files. Let's create a policy that allows deletion only if the user has a specific role, for example, an 'admin' role.

This requires a custom function to check user roles, or you can simplify by checking a specific `owner` UID if only one admin account exists.

CREATE POLICY "Allow admins to delete"
  ON storage.objects FOR DELETE
  TO authenticated
  USING (bucket_id = 'sensitive-data' AND auth.jwt() ->> 'user_role' = 'admin');

Testing Policies Effectively

After creating policies, it's crucial to test them thoroughly. You can do this by:

  • Logging in as different users: Test with authenticated users, unauthenticated users, and users with different roles.
  • Attempting forbidden actions: Try to upload, read, or delete files that your policies should prevent.
  • Using the Supabase client: Make API calls with supabase-js or other client libraries and observe the responses (e.g., expecting 403 Forbidden errors).

Always verify your policies work as intended before deploying to production.

Quick Policy Check

You've learned how to create various Storage policies. Which of the following conditions would allow an authenticated user to insert a file into a bucket named 'private-docs' ONLY if the file is placed in a folder matching their user ID?

Recap: Storage Policies

Great job! You've learned how to secure your Supabase Storage with policies. We covered:

  • The importance of RLS for storage buckets.
  • Creating policies for various actions (read, insert, delete).
  • Using auth.uid() and path_tokens for granular control.
  • Understanding the storage.objects table.

Implementing strong storage policies is crucial for the security and integrity of your application's file management.

常见问题解答

「使用策略管理访问权限」课时是免费的吗?

是的 — 「使用策略管理访问权限」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Supabase Backend as a Service 课程的其余内容,请升级到 CoddyKit PRO。 Supabase Backend as a Service 课程共包含 4 节课。

「使用策略管理访问权限」这节课中我会学到什么?

使用 Supabase Storage 策略为文件实现细粒度的访问控制,确保数据安全。 你通过在浏览器中直接运行的动手代码来练习 Supabase Backend as a Service,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Supabase Backend as a Service 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Supabase Backend as a Service 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「使用策略管理访问权限」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Supabase Backend as a Service 课中编写并运行代码吗?

能。每节 Supabase Backend as a Service 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 在 Supabase 存储桶中存储文件
  2. 使用策略管理访问权限
  3. 上传并获取媒体文件
  4. 图像转换与签名 URL
← 返回 Supabase Backend as a Service