FHSH OAuth Server 的官方 Python SDK,支援同步和非同步兩種版本。
基本安裝 (HTTP/1.1 only):
使用 pip:
pip install "git+https://github.com/fhsh-tp/fhsh-oauth-py-sdk.git"使用 uv:
uv add "git+https://github.com/fhsh-tp/fhsh-oauth-py-sdk.git"若需 HTTP/2 支援(額外安裝 httpx[http2]):
使用 pip:
pip install "fhsh-oauth-sdk[http2] @ git+https://github.com/fhsh-tp/fhsh-oauth-py-sdk.git"使用 uv:
uv add "git+https://github.com/fhsh-tp/fhsh-oauth-py-sdk.git[http2]"from fhsh_oauth import FHSHOAuthClient
import secrets
# 初始化客戶端
client = FHSHOAuthClient(
client_id="your-client-id",
client_secret="your-client-secret",
redirect_uri="https://yourapp.com/callback",
enable_http2=True # 啟用 HTTP/2 支援 (需安裝 [http2] extra)
)
# 1. 產生授權 URL
state = secrets.token_urlsafe(32)
auth_url = client.get_authorization_url(state=state)
# 重導向使用者至 auth_url
# 2. 使用者授權後,用 callback 中的 code 換取 token
token = client.exchange_code(code="callback-code")
# 3. 取得使用者資訊
userinfo = client.get_userinfo(token.access_token)
print(f"Hello, {userinfo.name}!")
# 4. 當 token 過期時,使用 refresh token 更新
new_token = client.refresh_token(token.refresh_token)
# 5. 登出時撤銷 token
client.revoke_token(token.access_token)from fhsh_oauth import AsyncFHSHOAuthClient
import secrets
async def main():
async with AsyncFHSHOAuthClient(
client_id="your-client-id",
client_secret="your-client-secret",
redirect_uri="https://yourapp.com/callback"
) as client:
# 產生授權 URL(同步方法)
state = secrets.token_urlsafe(32)
auth_url = client.get_authorization_url(state=state)
# 換取 token
token = await client.exchange_code(code="callback-code")
# 取得使用者資訊
userinfo = await client.get_userinfo(token.access_token)
print(f"Hello, {userinfo.name}!")from fhsh_oauth import (
FHSHOAuthClient,
AuthenticationError,
InvalidTokenError,
NetworkError,
)
try:
token = client.exchange_code(code="invalid-code")
except AuthenticationError:
print("認證失敗:Client ID 或 Secret 錯誤")
except InvalidTokenError:
print("授權碼無效或已過期")
except NetworkError:
print("無法連線至 OAuth Server")| 方法 | 說明 |
|---|---|
get_authorization_url(state, scope, nonce) |
產生授權 URL |
exchange_code(code) |
用授權碼換取 Token |
refresh_token(refresh_token) |
更新 Access Token |
get_userinfo(access_token) |
取得使用者資訊 |
introspect_token(token) |
驗證 Token 是否有效 |
revoke_token(token, token_type_hint) |
撤銷 Token |
get_discovery() |
取得 OIDC Discovery Document |
TokenResponse: Token 回應UserInfo: 使用者資訊IntrospectionResult: Token 驗證結果OIDCDiscovery: OIDC 配置文件
FHSHOAuthError: 基礎例外AuthenticationError: 認證失敗 (401)AuthorizationError: 授權失敗 (403)InvalidTokenError: Token 無效NetworkError: 網路錯誤ServerError: 伺服器錯誤 (5xx)ValidationError: 輸入驗證錯誤
# 安裝開發依賴
uv sync --dev
# 執行測試
uv run pytest
# 執行 linting
uv run ruff check fhsh_oauth/Educational Community License v2.0