Skip to content

建立 2026-09-14 更新 2026-09-14

使用者登入

Supabase Auth 幫你處理註冊、登入、重設密碼與第三方登入。成功之後,Client 會把 access token 附在後續請求上,資料庫才看得到 authenticated 角色與 auth.uid()

Email 與密碼

先在 Dashboard → Authentication → Providers 確認 Email 已開啟。開發階段可在 Authentication → Sign In / Providers 把「Confirm email」關掉,否則收不到信就登不進去。

const { data, error } = await supabase.auth.signUp({
  email: 'user@example.com',
  password: 'a-strong-password',
})

const { data: sessionData, error: signInError } =
  await supabase.auth.signInWithPassword({
    email: 'user@example.com',
    password: 'a-strong-password',
  })

data.user 是使用者列;data.session 含 access token 與 refresh token。之後 from('todos').select() 會自動帶這個 session,不必自己塞 header。

登出:

await supabase.auth.signOut()

讀目前使用者(向 Auth 伺服器確認,不要只信 localStorage 裡的物件):

const { data, error } = await supabase.auth.getUser()

其他登入方式

常見還有:

  • Magic Link:寄一封信,點了就登入,使用者不必記密碼。
  • OAuth:Google、GitHub 等。Dashboard 填 Client ID/Secret,前端呼叫 signInWithOAuth({ provider: 'github' })
  • 匿名登入:先當訪客,之後再升級成正式帳號。適合先體驗再註冊。

挑一種做完 RLS,再加第二種。每多一個 provider,就要測一次「登入後 auth.uid() 是否真的對應到你的 user_id」。

使用者資料放哪

Auth 把帳號存在 auth.users。這張表不要直接當公開資料表用。需要顯示名稱、頭像時,另外建 public.profiles,用觸發器在註冊時插入一列,主鍵等於 auth.uid()。官方 User Management 教學就是這個模式。

相關資料