supabase-auth

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Supabase Authentication

Supabase 认证

Overview

概述

This skill provides authentication and user management operations through the Supabase Auth API. Supports email/password authentication, session management, user metadata, and password recovery.
本技能通过Supabase Auth API提供认证和用户管理操作。支持邮箱/密码认证、会话管理、用户元数据以及密码恢复功能。

Prerequisites

前置条件

Required environment variables:
bash
export SUPABASE_URL="https://your-project.supabase.co"
export SUPABASE_KEY="your-anon-or-service-role-key"
Helper script: This skill uses the shared Supabase API helper. Make sure to source it:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"
必需的环境变量:
bash
export SUPABASE_URL="https://your-project.supabase.co"
export SUPABASE_KEY="your-anon-or-service-role-key"
辅助脚本: 本技能使用共享的Supabase API辅助脚本,请确保已加载它:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

Common Operations

常见操作

Sign Up - Create New User

注册 - 创建新用户

Basic email/password signup:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

supabase_post "/auth/v1/signup" '{
  "email": "user@example.com",
  "password": "securepassword123"
}'
Signup with user metadata:
bash
supabase_post "/auth/v1/signup" '{
  "email": "user@example.com",
  "password": "securepassword123",
  "data": {
    "first_name": "John",
    "last_name": "Doe",
    "age": 30
  }
}'
Auto-confirm user (requires service role key):
bash
undefined
基础邮箱/密码注册:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

supabase_post "/auth/v1/signup" '{
  "email": "user@example.com",
  "password": "securepassword123"
}'
携带用户元数据的注册:
bash
supabase_post "/auth/v1/signup" '{
  "email": "user@example.com",
  "password": "securepassword123",
  "data": {
    "first_name": "John",
    "last_name": "Doe",
    "age": 30
  }
}'
自动确认用户(需要服务角色密钥):
bash
undefined

Note: Use SUPABASE_KEY with service_role key for this

注意:此操作需将SUPABASE_KEY设置为service_role密钥

supabase_post "/auth/v1/signup" '{ "email": "user@example.com", "password": "securepassword123", "email_confirm": true }'
undefined
supabase_post "/auth/v1/signup" '{ "email": "user@example.com", "password": "securepassword123", "email_confirm": true }'
undefined

Sign In - Authenticate User

登录 - 验证用户身份

Email/password login:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

response=$(supabase_post "/auth/v1/token?grant_type=password" '{
  "email": "user@example.com",
  "password": "securepassword123"
}')
邮箱/密码登录:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

response=$(supabase_post "/auth/v1/token?grant_type=password" '{
  "email": "user@example.com",
  "password": "securepassword123"
}')

Extract access token

提取访问令牌

access_token=$(echo "$response" | jq -r '.access_token') refresh_token=$(echo "$response" | jq -r '.refresh_token')
echo "Access Token: $access_token" echo "Refresh Token: $refresh_token"

**Response includes:**
- `access_token` - JWT token for authenticated requests
- `refresh_token` - Token to get new access token when expired
- `user` - User object with id, email, metadata
- `expires_in` - Token expiration time in seconds
access_token=$(echo "$response" | jq -r '.access_token') refresh_token=$(echo "$response" | jq -r '.refresh_token')
echo "Access Token: $access_token" echo "Refresh Token: $refresh_token"

**响应包含:**
- `access_token` - 用于已认证请求的JWT令牌
- `refresh_token` - 当访问令牌过期时,用于获取新访问令牌的令牌
- `user` - 包含id、邮箱、元数据的用户对象
- `expires_in` - 令牌过期时间(秒)

Get Current User

获取当前用户

Retrieve user info with access token:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"
使用访问令牌获取用户信息:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

Set your access token from login

设置从登录获取的访问令牌

ACCESS_TOKEN="eyJhbGc..."
curl -s -X GET
"${SUPABASE_URL}/auth/v1/user"
-H "apikey: ${SUPABASE_KEY}"
-H "Authorization: Bearer ${ACCESS_TOKEN}"
undefined
ACCESS_TOKEN="eyJhbGc..."
curl -s -X GET
"${SUPABASE_URL}/auth/v1/user"
-H "apikey: ${SUPABASE_KEY}"
-H "Authorization: Bearer ${ACCESS_TOKEN}"
undefined

Update User

更新用户

Update user metadata:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

ACCESS_TOKEN="eyJhbGc..."

curl -s -X PUT \
    "${SUPABASE_URL}/auth/v1/user" \
    -H "apikey: ${SUPABASE_KEY}" \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    -H "Content-Type: application/json" \
    -d '{
      "data": {
        "first_name": "Jane",
        "avatar_url": "https://example.com/avatar.jpg"
      }
    }'
Update email:
bash
curl -s -X PUT \
    "${SUPABASE_URL}/auth/v1/user" \
    -H "apikey: ${SUPABASE_KEY}" \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    -H "Content-Type: application/json" \
    -d '{
      "email": "newemail@example.com"
    }'
Update password:
bash
curl -s -X PUT \
    "${SUPABASE_URL}/auth/v1/user" \
    -H "apikey: ${SUPABASE_KEY}" \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    -H "Content-Type: application/json" \
    -d '{
      "password": "newsecurepassword123"
    }'
更新用户元数据:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

ACCESS_TOKEN="eyJhbGc..."

curl -s -X PUT \
    "${SUPABASE_URL}/auth/v1/user" \
    -H "apikey: ${SUPABASE_KEY}" \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    -H "Content-Type: application/json" \
    -d '{
      "data": {
        "first_name": "Jane",
        "avatar_url": "https://example.com/avatar.jpg"
      }
    }'
更新邮箱:
bash
curl -s -X PUT \
    "${SUPABASE_URL}/auth/v1/user" \
    -H "apikey: ${SUPABASE_KEY}" \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    -H "Content-Type: application/json" \
    -d '{
      "email": "newemail@example.com"
    }'
更新密码:
bash
curl -s -X PUT \
    "${SUPABASE_URL}/auth/v1/user" \
    -H "apikey: ${SUPABASE_KEY}" \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    -H "Content-Type: application/json" \
    -d '{
      "password": "newsecurepassword123"
    }'

Sign Out

登出

Sign out user (invalidate refresh token):
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

ACCESS_TOKEN="eyJhbGc..."

curl -s -X POST \
    "${SUPABASE_URL}/auth/v1/logout" \
    -H "apikey: ${SUPABASE_KEY}" \
    -H "Authorization: Bearer ${ACCESS_TOKEN}"
用户登出(使刷新令牌失效):
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

ACCESS_TOKEN="eyJhbGc..."

curl -s -X POST \
    "${SUPABASE_URL}/auth/v1/logout" \
    -H "apikey: ${SUPABASE_KEY}" \
    -H "Authorization: Bearer ${ACCESS_TOKEN}"

Refresh Token

刷新令牌

Get new access token using refresh token:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

REFRESH_TOKEN="your-refresh-token"

supabase_post "/auth/v1/token?grant_type=refresh_token" '{
  "refresh_token": "'"${REFRESH_TOKEN}"'"
}'
使用刷新令牌获取新的访问令牌:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

REFRESH_TOKEN="your-refresh-token"

supabase_post "/auth/v1/token?grant_type=refresh_token" '{
  "refresh_token": "'"${REFRESH_TOKEN}"'"
}'

Password Recovery

密码恢复

Send password reset email:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

supabase_post "/auth/v1/recover" '{
  "email": "user@example.com"
}'
Reset password with recovery token:
bash
undefined
发送密码重置邮件:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

supabase_post "/auth/v1/recover" '{
  "email": "user@example.com"
}'
使用恢复令牌重置密码:
bash
undefined

This is typically done through email link

此操作通常通过邮件链接完成

The recovery token comes from the email link

恢复令牌来自邮件链接

RECOVERY_TOKEN="token-from-email"
curl -s -X PUT
"${SUPABASE_URL}/auth/v1/user"
-H "apikey: ${SUPABASE_KEY}"
-H "Authorization: Bearer ${RECOVERY_TOKEN}"
-H "Content-Type: application/json"
-d '{ "password": "newpassword123" }'
undefined
RECOVERY_TOKEN="token-from-email"
curl -s -X PUT
"${SUPABASE_URL}/auth/v1/user"
-H "apikey: ${SUPABASE_KEY}"
-H "Authorization: Bearer ${RECOVERY_TOKEN}"
-H "Content-Type: application/json"
-d '{ "password": "newpassword123" }'
undefined

Resend Confirmation Email

重新发送确认邮件

Resend email verification:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

supabase_post "/auth/v1/resend" '{
  "type": "signup",
  "email": "user@example.com"
}'
重新发送邮箱验证邮件:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

supabase_post "/auth/v1/resend" '{
  "type": "signup",
  "email": "user@example.com"
}'

Admin Operations (Service Role Key Required)

管理员操作(需要服务角色密钥)

List All Users

列出所有用户

Get all users (requires service role key):
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"
获取所有用户(需要服务角色密钥):
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

Make sure SUPABASE_KEY is set to service_role key

确保SUPABASE_KEY设置为service_role密钥

supabase_get "/auth/v1/admin/users"

**Paginated user list:**
```bash
supabase_get "/auth/v1/admin/users"

**分页获取用户列表:**
```bash

Get users with pagination

分页获取用户

supabase_get "/auth/v1/admin/users?page=1&per_page=50"
undefined
supabase_get "/auth/v1/admin/users?page=1&per_page=50"
undefined

Get User by ID

通过ID获取用户

Retrieve specific user (requires service role key):
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

USER_ID="user-uuid-here"

supabase_get "/auth/v1/admin/users/${USER_ID}"
获取特定用户(需要服务角色密钥):
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

USER_ID="user-uuid-here"

supabase_get "/auth/v1/admin/users/${USER_ID}"

Create User (Admin)

管理员创建用户

Create user without email confirmation:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

supabase_post "/auth/v1/admin/users" '{
  "email": "admin-created@example.com",
  "password": "securepassword123",
  "email_confirm": true,
  "user_metadata": {
    "first_name": "Admin",
    "last_name": "Created"
  }
}'
创建无需邮箱确认的用户:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

supabase_post "/auth/v1/admin/users" '{
  "email": "admin-created@example.com",
  "password": "securepassword123",
  "email_confirm": true,
  "user_metadata": {
    "first_name": "Admin",
    "last_name": "Created"
  }
}'

Update User (Admin)

管理员更新用户

Update user as admin:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

USER_ID="user-uuid-here"

curl -s -X PUT \
    "${SUPABASE_URL}/auth/v1/admin/users/${USER_ID}" \
    -H "apikey: ${SUPABASE_KEY}" \
    -H "Authorization: Bearer ${SUPABASE_KEY}" \
    -H "Content-Type: application/json" \
    -d '{
      "email": "updated@example.com",
      "user_metadata": {
        "role": "admin"
      }
    }'
以管理员身份更新用户:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

USER_ID="user-uuid-here"

curl -s -X PUT \
    "${SUPABASE_URL}/auth/v1/admin/users/${USER_ID}" \
    -H "apikey: ${SUPABASE_KEY}" \
    -H "Authorization: Bearer ${SUPABASE_KEY}" \
    -H "Content-Type: application/json" \
    -d '{
      "email": "updated@example.com",
      "user_metadata": {
        "role": "admin"
      }
    }'

Delete User (Admin)

管理员删除用户

Delete user account:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

USER_ID="user-uuid-here"

supabase_delete "/auth/v1/admin/users/${USER_ID}"
删除用户账号:
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

USER_ID="user-uuid-here"

supabase_delete "/auth/v1/admin/users/${USER_ID}"

Common Patterns

常见模式

Login and Store Tokens

登录并存储令牌

bash
#!/bin/bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"
bash
#!/bin/bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

Login

登录

response=$(supabase_post "/auth/v1/token?grant_type=password" '{ "email": "user@example.com", "password": "password123" }')
response=$(supabase_post "/auth/v1/token?grant_type=password" '{ "email": "user@example.com", "password": "password123" }')

Extract tokens

提取令牌

access_token=$(echo "$response" | jq -r '.access_token') refresh_token=$(echo "$response" | jq -r '.refresh_token') user_id=$(echo "$response" | jq -r '.user.id')
access_token=$(echo "$response" | jq -r '.access_token') refresh_token=$(echo "$response" | jq -r '.refresh_token') user_id=$(echo "$response" | jq -r '.user.id')

Store in environment or file for subsequent requests

存储到环境变量或文件中,供后续请求使用

export SUPABASE_ACCESS_TOKEN="$access_token" export SUPABASE_REFRESH_TOKEN="$refresh_token" export SUPABASE_USER_ID="$user_id"
echo "Logged in as user: $user_id"
undefined
export SUPABASE_ACCESS_TOKEN="$access_token" export SUPABASE_REFRESH_TOKEN="$refresh_token" export SUPABASE_USER_ID="$user_id"
echo "Logged in as user: $user_id"
undefined

Check if User Exists

检查用户是否存在

bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"
bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

Note: This requires service role key and admin endpoint

注意:此操作需要服务角色密钥和管理员端点

email="check@example.com"
users=$(supabase_get "/auth/v1/admin/users") exists=$(echo "$users" | jq --arg email "$email" '.users[] | select(.email == $email)')
if [[ -n "$exists" ]]; then echo "User exists" else echo "User does not exist" fi
undefined
email="check@example.com"
users=$(supabase_get "/auth/v1/admin/users") exists=$(echo "$users" | jq --arg email "$email" '.users[] | select(.email == $email)')
if [[ -n "$exists" ]]; then echo "User exists" else echo "User does not exist" fi
undefined

Verify JWT Token

验证JWT令牌

bash
undefined
bash
undefined

Tokens are JWTs - you can decode them (requires jq)

令牌为JWT格式 - 可解码(需要jq)

ACCESS_TOKEN="eyJhbGc..."
ACCESS_TOKEN="eyJhbGc..."

Decode payload (base64)

解码负载(base64)

payload=$(echo "$ACCESS_TOKEN" | cut -d. -f2 | base64 -d 2>/dev/null) echo "$payload" | jq '.'
payload=$(echo "$ACCESS_TOKEN" | cut -d. -f2 | base64 -d 2>/dev/null) echo "$payload" | jq '.'

Check expiration

检查过期时间

exp=$(echo "$payload" | jq -r '.exp') now=$(date +%s)
if [[ $now -gt $exp ]]; then echo "Token expired" else echo "Token valid" fi
undefined
exp=$(echo "$payload" | jq -r '.exp') now=$(date +%s)
if [[ $now -gt $exp ]]; then echo "Token expired" else echo "Token valid" fi
undefined

Error Handling

错误处理

Common error responses:
StatusErrorMeaning
400Invalid login credentialsWrong email or password
400User already registeredEmail already exists
401Invalid tokenAccess token expired or invalid
422Validation errorInvalid email format or weak password
429Too many requestsRate limit exceeded
bash
if response=$(supabase_post "/auth/v1/token?grant_type=password" '{...}' 2>&1); then
    echo "Login successful"
    access_token=$(echo "$response" | jq -r '.access_token')
else
    echo "Login failed: $response"
    exit 1
fi
常见错误响应:
状态码错误信息含义
400Invalid login credentials邮箱或密码错误
400User already registered邮箱已被注册
401Invalid token访问令牌过期或无效
422Validation error邮箱格式无效或密码强度不足
429Too many requests请求次数超出限制
bash
if response=$(supabase_post "/auth/v1/token?grant_type=password" '{...}' 2>&1); then
    echo "Login successful"
    access_token=$(echo "$response" | jq -r '.access_token')
else
    echo "Login failed: $response"
    exit 1
fi

Security Best Practices

安全最佳实践

  1. Never commit credentials: Store tokens in environment variables or secure files
  2. Use anon key for client operations: Public-facing authentication
  3. Use service role key carefully: Admin operations only, never expose to clients
  4. Implement token refresh: Refresh access tokens before they expire
  5. Enable RLS: Configure Row Level Security policies in Supabase dashboard
  6. Validate tokens server-side: Don't trust client-provided tokens without verification
  1. 切勿提交凭据:将令牌存储在环境变量或安全文件中
  2. 客户端操作使用匿名密钥:面向公众的认证操作
  3. 谨慎使用服务角色密钥:仅用于管理员操作,切勿暴露给客户端
  4. 实现令牌刷新:在访问令牌过期前刷新
  5. 启用RLS:在Supabase控制台配置行级安全策略
  6. 服务端验证令牌:不要信任客户端提供的令牌,需进行验证

Session Management

会话管理

Typical flow:
  1. User signs in → Get access_token and refresh_token
  2. Store tokens securely
  3. Use access_token in Authorization header for authenticated requests
  4. When access_token expires → Use refresh_token to get new access_token
  5. User signs out → Invalidate refresh_token
Token lifespan:
  • Access token: 1 hour (default)
  • Refresh token: 30 days (default)
典型流程:
  1. 用户登录 → 获取access_token和refresh_token
  2. 安全存储令牌
  3. 在已认证请求的Authorization头中使用access_token
  4. 当access_token过期 → 使用refresh_token获取新的access_token
  5. 用户登出 → 使refresh_token失效
令牌有效期:
  • 访问令牌:1小时(默认)
  • 刷新令牌:30天(默认)

API Documentation

API文档

Full Supabase Auth API documentation: https://supabase.com/docs/guides/auth
完整的Supabase Auth API文档:https://supabase.com/docs/guides/auth