OAuth 2.0 授權碼流程

Vibe Prompt

「幫我實作 OAuth 2.0 Authorization Code + PKCE Flow,用 Supabase 做 Identity Provider。」

流程

1. 前端 → Supabase: 跳轉到授權頁面
   GET https://<project>.supabase.co/auth/v1/authorize
     ?client_id=<client_id>
     &redirect_uri=<redirect_uri>
     &response_type=code
     &code_challenge=<SHA256(code_verifier)>
     &code_challenge_method=S256
     &scope=openid profile email

2. 使用者登入並授權

3. Supabase → 前端: 跳轉回 redirect_uri 帶授權碼
   https://myapp.com/auth/callback?code=<auth_code>

4. 前端 → 後端: 傳授權碼

5. 後端 → Supabase: 換取 Token
   POST https://<project>.supabase.co/auth/v1/token
     ?grant_type=authorization_code
     &code=<auth_code>
     &code_verifier=<original_code_verifier>
     &redirect_uri=<redirect_uri>

6. Supabase → 後端: access_token + refresh_token + id_token

7. 後端 → 前端: 設定 Session Cookie

Next.js API Route

// app/api/auth/callback/route.ts
import { createClient } from '@/utils/supabase/server'
import { NextResponse } from 'next/server'

export async function GET(request: Request) {
  const { searchParams, origin } = new URL(request.url)
  const code = searchParams.get('code')
  const next = searchParams.get('next') ?? '/'
  
  if (code) {
    const supabase = createClient()
    const { error } = await supabase.auth.exchangeCodeForSession(code)
    if (!error) {
      return NextResponse.redirect(`${origin}${next}`)
    }
  }
  
  return NextResponse.redirect(`${origin}/auth-error`)
}

PKCE 好處

  • ✅ 授權碼在傳輸中被攔截也無法使用(需要 code_verifier)
  • ✅ 不需要 client_secret(適合 SPA)
  • ✅ 防止授權碼攔截攻擊

解鎖完整教學內容

本章為付費內容。加入專案即可解鎖超過 5000 字的深度解析,包含 10 個以上神級 Prompt 與真實 Source Code 範例!