使用 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错误处理为正常取消。否则,在使用代码之前比较返回的 state 与保存的值。拒绝缺失或不匹配的状态。一旦使用保存的状态,不接受由其他浏览器会话提交的回调URL。
3. 交换代码#
POST
https://auth.shareai.now/oauth/token交换一次性代码和匹配的PKCE验证器。
- 基础 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. 存储结果并建立您的应用程序会话#
在您的后端存储访问和刷新令牌。使用返回的 expires_in 而不是假设永久令牌。如果您使用ID令牌,请在信任声明之前使用发行者的JWKS、预期发行者、客户端受众、过期时间和您的原始随机数验证其签名。
继续生命周期#
最近更新于 9 月 15, 2026