OAuth2
OAuth2 驗證
讓其他 Sofia 帳號連結你的應用程式:註冊用戶端,執行帶 PKCE 的授權碼流程,更新權杖並申請合適的 scope。
OAuth:授權碼 + PKCE
在設定 › API › 應用程式用戶端中註冊用戶端:名稱、Logo、隱私權政策、可申請的權限,以及 https 重新導向 URL。機密(confidential)用戶端有密鑰;公開(public)用戶端(行動應用程式、瀏覽器擴充功能)沒有密鑰,僅依靠 PKCE。
帶上 PKCE 挑戰碼(必須使用 S256)和保存在使用者工作階段中的 state,將使用者導向授權端點:
import { createHash, randomBytes } from 'node:crypto';
const verifier = randomBytes(32).toString('base64url');
const challenge = createHash('sha256').update(verifier).digest('base64url');
const state = randomBytes(16).toString('base64url');
const url = new URL('https://api.sofia-post.com/api/v1/oauth/authorize');
url.search = new URLSearchParams({
response_type: 'code',
client_id: process.env.SOFIA_CLIENT_ID,
redirect_uri: 'https://app.example.com/oauth/callback',
scope: 'establishments:read posts:read posts:write offline_access',
state,
code_challenge: challenge,
code_challenge_method: 'S256',
}).toString();使用者登入 Sofia,看到你的名稱、Logo 和權限,選擇一個 Workspace 並同意。接著 Sofia 會帶著 code、你的 state 和簽發者 iss 將使用者送回你的重新導向 URL。驗證 state 和 iss 後,再兌換授權碼:
curl -X POST https://api.sofia-post.com/api/v1/oauth/token \
-u "$SOFIA_CLIENT_ID:$SOFIA_CLIENT_SECRET" \
-d grant_type=authorization_code \
-d code=$CODE \
-d redirect_uri=https://app.example.com/oauth/callback \
-d code_verifier=$VERIFIER{
"access_token": "sofia_live_at_…",
"token_type": "Bearer",
"expires_in": 3600,
"scope": "establishments:read posts:read posts:write offline_access",
"refresh_token": "sofia_live_rt_…"
}- 授權碼有效期限為 5 分鐘,且只能使用一次。重複使用會被拒絕,並且它簽發的權杖會失效。
- 存取權杖有效期限為一小時,且僅對使用者所選的 Workspace 生效。
- 只有在你申請了
offline_access時才會回傳refresh_token。它只能使用一次:每次都要保存新的。重複使用已用過的更新權杖會撤銷整個授權。
curl -X POST https://api.sofia-post.com/api/v1/oauth/token \
-u "$SOFIA_CLIENT_ID:$SOFIA_CLIENT_SECRET" \
-d grant_type=refresh_token \
-d refresh_token=$REFRESH_TOKENOAuth:用戶端憑證
機密用戶端也可以在不需使用者參與的情況下,對其擁有者持有的 Workspace 進行操作。當用戶端持有多個 Workspace 時,請用 workspace_id 指定其中一個。
curl -X POST https://api.sofia-post.com/api/v1/oauth/token \
-u "$SOFIA_CLIENT_ID:$SOFIA_CLIENT_SECRET" \
-d grant_type=client_credentials \
-d workspace_id=$WORKSPACE_ID權限(scope)
| Scope | 允許 |
|---|---|
establishments:read | 列出門市 |
accounts:read, accounts:write | 讀取已連結的網路;建立連結用的連結 |
media:read, media:write | 讀取媒體庫;上傳和匯入媒體 |
posts:read, posts:write | 列出和追蹤貼文;發布、編輯和刪除貼文 |
insights:read | 讀取統計資料 |
webhooks:read, webhooks:write | 列出 webhook;註冊、測試和刪除 webhook |
offline_access | 僅限 OAuth:接收更新權杖 |
缺少所需 scope 的呼叫會回傳 403 insufficient_scope。伺服器中繼資料(RFC 8414)列出了所有端點和 scope:
https://api.sofia-post.com/.well-known/oauth-authorization-server/api/v1/oauth