认证配置
SOVR SDK 支持多种认证方式,本文档介绍如何配置和管理 API 认证。
API Key 认证
最简单的认证方式是使用 API Key。
获取 API Key
- 登录 SOVR 控制台
- 进入 设置 > API Keys
- 点击 创建 API Key
- 复制生成的 Key(注意:Key 只显示一次)
配置 API Key
python
from sovr_sdk import SOVRClient
# 方式 1: 直接传入
client = SOVRClient(
base_url="https://api.sovr.ai",
api_key="sk_live_xxxxxxxxxxxx"
)
# 方式 2: 使用环境变量
import os
os.environ["SOVR_API_KEY"] = "sk_live_xxxxxxxxxxxx"
client = SOVRClient(
base_url="https://api.sovr.ai"
) # 自动读取环境变量typescript
import { SOVRClient } from '@sovr/sdk';
// 方式 1: 直接传入
const client = new SOVRClient({
baseUrl: 'https://api.sovr.ai',
apiKey: 'sk_live_xxxxxxxxxxxx'
});
// 方式 2: 使用环境变量
process.env.SOVR_API_KEY = 'sk_live_xxxxxxxxxxxx';
const client = new SOVRClient({
baseUrl: 'https://api.sovr.ai'
}); // 自动读取环境变量沙盒环境
在开发和测试阶段,建议使用沙盒环境。
沙盒 API Key
沙盒 API Key 以 sk_sandbox_ 开头,具有以下特点:
- 隔离的测试环境
- 不影响生产数据
- 有限的请求配额
- 数据自动清理(默认 7 天)
配置沙盒环境
python
client = SOVRClient(
base_url="https://sandbox.api.sovr.ai",
api_key="sk_sandbox_xxxxxxxxxxxx"
)typescript
const client = new SOVRClient({
baseUrl: 'https://sandbox.api.sovr.ai',
apiKey: 'sk_sandbox_xxxxxxxxxxxx'
});API Key 权限
API Key 可以配置不同的权限范围:
| 权限 | 说明 |
|---|---|
read | 读取数据 |
write | 创建和修改数据 |
delete | 删除数据 |
admin | 管理员权限 |
创建受限 API Key
python
# 只读 API Key
client.create_api_key(
name="Read Only Key",
permissions=["read"]
)
# 读写 API Key
client.create_api_key(
name="Read Write Key",
permissions=["read", "write"]
)安全最佳实践
1. 保护 API Key
重要
永远不要在客户端代码或公开仓库中暴露 API Key。
- 使用环境变量存储 API Key
- 不要将 API Key 提交到版本控制
- 定期轮换 API Key
2. 使用最小权限
只授予 API Key 必要的权限:
python
# ✅ 好的做法:只授予必要权限
client.create_api_key(
name="Audit Reader",
permissions=["read"]
)
# ❌ 避免:授予过多权限
client.create_api_key(
name="Full Access",
permissions=["read", "write", "delete", "admin"]
)3. 设置过期时间
为 API Key 设置合理的过期时间:
python
from datetime import datetime, timedelta
client.create_api_key(
name="Temporary Key",
permissions=["read", "write"],
expires_at=datetime.now() + timedelta(days=30)
)4. 监控 API Key 使用
定期检查 API Key 的使用情况:
python
# 获取 API Key 使用统计
stats = client.get_api_key_stats(key_id="key_xxxx")
print(f"Last used: {stats.last_used_at}")
print(f"Request count: {stats.request_count}")错误处理
认证错误
python
from sovr_sdk.exceptions import AuthenticationError
try:
client = SOVRClient(
base_url="https://api.sovr.ai",
api_key="invalid_key"
)
client.list_decisions()
except AuthenticationError as e:
print(f"认证失败: {e.message}")
# 处理认证错误typescript
import { SOVRClient, AuthenticationError } from '@sovr/sdk';
try {
const client = new SOVRClient({
baseUrl: 'https://api.sovr.ai',
apiKey: 'invalid_key'
});
await client.listDecisions();
} catch (error) {
if (error instanceof AuthenticationError) {
console.error(`认证失败: ${error.message}`);
// 处理认证错误
}
}常见错误码
| 错误码 | 说明 | 解决方案 |
|---|---|---|
401 | API Key 无效 | 检查 API Key 是否正确 |
403 | 权限不足 | 检查 API Key 权限 |
429 | 请求过于频繁 | 降低请求频率 |