1
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 Google OAuth認証で401エラーが発生する場合の対処法

Posted at

概要

SupabaseとNext.jsを使ったWebアプリケーションで、Google OAuth認証を実装した際に以下のエラーが発生しました。

  GET https://xxx.supabase.co/auth/v1/user 401 (Unauthorized)
  Auth state changed: SIGNED_OUT

結論から言うと、Legacy API Keys を使用していることが原因でした。
新しい Publishable Key に移行することで解決しました。

発生した問題

環境

  • Next.js 14 (TypeScript)
  • Supabase
  • Railway (デプロイ先)
  • Google OAuth認証

エラーの症状

  1. Google 認証画面では正常にログインできる
  2. しかし 、認証後に Supabase の /auth/v1/user エンドポイントで 401 エラー
  3. 認証状態が SIGNED_OUT になってしまう
  4. ローカル環境では動作するが、本番環境でエラーが発生

エラーログ

  GET https://xxxxxxxxxxxx.supabase.co/auth/v1/user 401 (Unauthorized)
  Auth state changed: SIGNED_OUT
  Auth state changed: INITIAL_SESSION

原因の特定

調査の過程

  1. Google Cloud Console の設定確認 → 正常
  2. Supabase Auth の Google Provider 設定確認 → 正常
  3. 環境変数の確認 → URL、Keyとも正常に読み込まれている
  4. API Key の種類を確認 → Legacy API Keys を使用していることが判明

根本原因

Legacy API Keys は古い形式のAPIキーで、最新の Supabase 認証機能と互換性のない場合があるとのこと。

Check whether JWT based legacy (anon, service_role) API keys are enabled. This API endpoint will be removed in the future, check for HTTP 404 Not Found.

解決方法

新しい API Key を作成

  1. Supabase ダッシュボードにアクセス
  2. Project Settings → API Keys をクリック
  3. API Keys タブ(Legacy API Keysではない方)を選択
  4. 新しい API Kesy が作成されていない場合、Create API keys で作成
  5. Publishable key を確認・コピー

下記のように対応しているものと思われます。

Lergacy API Keys と API Keys の対応
Lergacy API Keys API Keys
anon | public Publishable key
service_role | secret Secret keys

新しい Publishable key の形式

sb_publishable_xxxxxxxxxxxxxxxxxx

環境変数を更新

  1. ローカル環境(.env.local)の環境変数更新
  2. デプロイ先の環境変数も同様に更新
  3. アプリケーションを再デプロイ
.env.local
NEXT_PUBLIC_SUPABASE_ANON_KEY=sb_publishable_xxxxxxxxxxxxxxxxxx

結果

新しいPublishable Keyに移行後、Google OAuth認証が正常に動作するようになりました。

まとめ

Supabase で Legacy API Keys を使用している場合、 Publishable Keys への移行が必要のようです。特に以下の場合は確認にしてみると良いと思います。

  • 認証周りで401エラーが発生している
  • ローカル環境では動作するが本番環境でエラーが出る
  • 古い Supabase プロジェクトを使用している

チェックポイント

  • Supabaseダッシュボードで API Keys タブを確認
  • sb_publishable_で始まるキーを使用している
  • 環境変数が正しく設定されている

同じエラーでつまづいた方に少しでもお役に立てば幸いです。

1
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
1
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?