2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【supabase】RLS設定とエラー解決例(406/403エラー対応)

Posted at

問題

supabaseにデータを登録したところ、エラーが出て登録できない。
Chromeのデベロッパーツールツールで、確認すると以下エラーとなっていた。

  • 406 Not Acceptable エラー
  • 403 Forbidden エラー

image.png

前提条件

Enable Row Level Security(RLS)を有効にしている。
image.png

RLSとは(copilotで確認)

SupabaseのRLS(Row Level Security/行レベルセキュリティ)とは、データベースの各行ごとに「誰がアクセスできるか」を制御できるセキュリティ機能。

解決方法

テーブルごとに、SQLで「ポリシー(条件)」を設定する。
ポリシー(条件)はPostgreSQL標準の機能で、Supabaseでもそのまま利用できる。

たとえば、「ログインユーザーは自分のuser_idのデータだけ読める」「未ログインユーザーはuser_idがnullのデータだけ読める」など、柔軟なアクセス制御が可能。

  • Supabaseプロジェクトのダッシュボードにログイン
  • 左メニューから「SQL Editor(SQLエディタ)」を選択
  • 「New Query(新しいクエリ)」をクリック

image.png

image.png

下記のSQLを貼り付けて「Run(実行)」ボタンを押す。

.sql
-- 例: 自分のuser_idのレコードだけSELECT/INSERTことができる
-- (ALLなのでUPDATE, DELETEもできる)
CREATE POLICY "Users can manage their own profiles"
ON user_profiles
FOR ALL
USING (auth.uid() = user_id);

image.png

設定後、エラーが消えた。
image.png

終わりに

RLSがよくわからなかったのですが、理解できました。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?