0Pricing
Supabase Backend as a Service · Урок

Управление доступом с помощью политик

Реализуйте детализированный контроль доступа к файлам с помощью политик Supabase Storage, обеспечивая безопасность данных.

«Управление доступом с помощью политик» — бесплатный урок Supabase Backend as a Service на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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.

Часто задаваемые вопросы

Урок «Управление доступом с помощью политик» бесплатный?

Да — полный текст урока «Управление доступом с помощью политик» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Supabase Backend as a Service, подпишись на CoddyKit PRO. Курс Supabase Backend as a Service содержит 4 уроков всего.

Чему я научусь в уроке «Управление доступом с помощью политик»?

Реализуйте детализированный контроль доступа к файлам с помощью политик Supabase Storage, обеспечивая безопасность данных. Ты практикуешь Supabase Backend as a Service с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Supabase Backend as a Service?

Предыдущий опыт не требуется. Supabase Backend as a Service на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 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