0
0

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で“誰が何を見るか”をシンプルに制御する方法

0
Posted at

Supabase の Auth と Row Level Security(RLS)は、「ユーザー認証」と「データの閲覧権限」 を別々に管理しながら、最小限のコードで安全なアプリを作れる組み合わせです。初心者でも「自分のデータだけ見せたい」「他のユーザーのデータは隠したい」ことを、SQL のみで実現できます。

1. Supabase Auth の役割

Auth はメールアドレスや OAuth でユーザーを認証し、auth.uid() という関数で現在ログイン中のユーザー ID を取得できるようにします。フロントエンドでは supabase.auth.signIn() でサインインし、サーバー側では同じ ID が自動的にリクエストに付与されます。

2. Row Level Security とは

RLS はテーブル単位で「行ごとのアクセス制御」を行う機能です。ポリシーを作成すると、SELECT・INSERT・UPDATE・DELETE の各操作に対して条件式を設定できます。条件式の中で auth.uid() が使えるため、認証情報と紐付いた制御が可能です。

3. 具体的な流れ

  1. テーブル作成
    create table posts (
      id uuid primary key default uuid_generate_v4(),
      user_id uuid not null,
      title text,
      content text,
      created_at timestamp default now()
    );
    
  2. RLS 有効化
    alter table posts enable row level security;
    
  3. ポリシー追加
    create policy "owner can read/write"
      on posts
      for all
      using (auth.uid() = user_id);
    
    このポリシーは「レコードの user_id が現在ログイン中のユーザー ID と一致する場合だけ、すべての操作を許可」します。

4. フロントエンドでの使い方(例:Next.js)

import { createClient } from '@supabase/supabase-js';

const supabase = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);

// ログイン後に自分の投稿だけ取得
async function fetchMyPosts() {
  const { data, error } = await supabase
    .from('posts')
    .select('*'); // RLS が自動でフィルタリング
  if (error) console.error(error);
  return data;
}

認証情報は自動でヘッダーに付与され、サーバー側の RLS が「自分の投稿だけ」を返します。

5. まとめ

  • Auth が「誰が」アクセスしているかを管理。
  • RLS が「どの行に」アクセスできるかを制御。
  • 両者を組み合わせるだけで、バックエンドのコードを書かずに安全なデータ分離が実現できます。

実際のプロジェクトで試すと、認可ロジックが減り、保守性が格段に上がります。ぜひ自分のアプリに取り入れてみてください。

詳しい手順はこちら → https://felixstudio0.gumroad.com/?utm_source=qiita&utm_medium=github_actions&utm_campaign=2026-q1&utm_content=qiita-footer

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?