用 PKCE 授權客戶
使用 S256 PKCE 實現 ShareAI 授權碼流程,驗證狀態並喺你嘅應用程式後端交換代碼。
喺呢頁面
呢個流程將一個客戶帳戶連接到你嘅應用程式。客戶登入,揀選個人或者組織帳戶,並批准請求嘅權限。你嘅後端然後會用短期代碼交換令牌。
開始之前#
完成 應用程式註冊。你需要一個準確註冊嘅回調、伺服器持有嘅客戶端憑證同埋一個伺服器端會話,完成授權嘅瀏覽器需要呢啲條件。
1. 建立授權請求#
GET
https://auth.shareai.now/oauth/authorize要求客戶授權應用程式。
- 基礎 URL
https://auth.shareai.now- 認證
- 瀏覽器重定向;已註冊應用程式
每次嘗試都生成一個新嘅驗證碼、狀態同埋隨機數。將佢哋儲存喺啟動用戶嘅伺服器端會話中。喺瀏覽器重定向中發送 SHA-256 挑戰,永遠唔好發送驗證碼。只請求你嘅應用程式需要嘅範圍。
Python
import base64
import hashlib
import secrets
import urllib.parse
verifier = secrets.token_urlsafe(48)
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
state = secrets.token_urlsafe(32)
nonce = secrets.token_urlsafe(32)
# Store verifier, state and nonce in the user's server-side session.
params = {
"response_type": "code",
"client_id": "YOUR_CLIENT_ID",
"redirect_uri": "https://app.example.com/auth/shareai/callback",
"scope": "openid profile surcharge",
"state": state,
"nonce": nonce,
"code_challenge": challenge,
"code_challenge_method": "S256",
}
print("https://auth.shareai.now/oauth/authorize?" + urllib.parse.urlencode(params))
TypeScript
import { randomBytes, createHash } from "node:crypto";
const verifier = randomBytes(48).toString("base64url");
const state = randomBytes(32).toString("base64url");
const nonce = randomBytes(32).toString("base64url");
const challenge = createHash("sha256").update(verifier).digest("base64url");
// Save verifier, state and nonce in the initiating server-side session.
const params = new URLSearchParams({ response_type: "code", client_id: "YOUR_CLIENT_ID",
redirect_uri: "https://app.example.com/auth/shareai/callback",
scope: "openid profile surcharge", state, nonce,
code_challenge: challenge, code_challenge_method: "S256" });
const authorizationUrl = `https://auth.shareai.now/oauth/authorize?${params}`;
// Redirect the browser to authorizationUrl.
2. 驗證回調#
如果授權被拒絕,將 OAuth 錯誤處理為正常取消。否則,喺使用代碼之前,將返回嘅值同儲存嘅值進行比較。拒絕缺失或者唔匹配嘅狀態。一旦使用咗儲存嘅狀態,就唔好接受由其他瀏覽器會話提交嘅回調 URL。 state 交換一次性代碼同匹配嘅 PKCE 驗證碼。
3. 交換代碼#
POST
https://auth.shareai.now/oauth/token機密客戶端認證.
- 基礎 URL
https://auth.shareai.now- 認證
- 使用為客戶端配置嘅客戶端認證方法。示例使用基於表單嘅客戶端認證。唔好兩次發送相同嘅代碼;喺代碼被使用或者過期後重新開始授權。
cURL
curl --fail-with-body "https://auth.shareai.now/oauth/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
--data-urlencode "grant_type=authorization_code" \
--data-urlencode "client_id=$SHAREAI_CLIENT_ID" \
--data-urlencode "client_secret=$SHAREAI_CLIENT_SECRET" \
--data-urlencode "code=$AUTHORIZATION_CODE" \
--data-urlencode "redirect_uri=https://app.example.com/auth/shareai/callback" \
--data-urlencode "code_verifier=$PKCE_VERIFIER"
喺你嘅後端儲存訪問同刷新令牌。使用返回嘅.
4. 儲存結果並建立你嘅應用程式會話#
,而唔係假設係永久令牌。如果你使用 ID 令牌,喺信任聲明之前,用發行者嘅 JWKS、預期發行者、客戶端受眾、到期時間同你原始嘅隨機數驗證佢嘅簽名。 expires_in 令牌嘅兩種用途.
繼續生命週期#
範圍同帳戶身份 · OAuth 聊天請求 · 開始之前嘅連結
最後更新日期:2026年9月15日