认证机制
API 密钥认证
获取 API 密钥
- 登录 OpenHuman Dashboard
- 进入「设置」→「API 密钥」
- 点击「创建新密钥」
- 复制生成的密钥
使用 API 密钥
在请求 Header 中包含密钥:
curl -H "Authorization: Bearer YOUR_API_KEY" \
https://api.openhuman.ai/v1/agents
在代码中使用:
const client = new OpenHuman({
apiKey: 'YOUR_API_KEY',
});
OAuth 2.0
授权流程
用户 → 授权页面 → 授权成功 → 获取 code → 交换 token
实现 OAuth
// 1. 重定向用户到授权页面
const authUrl = `https://auth.openhuman.ai/oauth/authorize?
client_id=YOUR_CLIENT_ID&
redirect_uri=YOUR_REDIRECT_URI&
response_type=code&
scope=read write`;
window.location.href = authUrl;
// 2. 交换 access_token
const response = await fetch('https://auth.openhuman.ai/oauth/token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
grant_type: 'authorization_code',
code: authCode,
client_id: 'YOUR_CLIENT_ID',
client_secret: 'YOUR_CLIENT_SECRET',
redirect_uri: 'YOUR_REDIRECT_URI',
}),
});
const { access_token } = await response.json();
刷新 Token
const response = await fetch('https://auth.openhuman.ai/oauth/token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
grant_type: 'refresh_token',
refresh_token: refreshToken,
client_id: 'YOUR_CLIENT_ID',
client_secret: 'YOUR_CLIENT_SECRET',
}),
});
权限控制
权限级别
| 权限 | 说明 |
|---|---|
read | 读取数据 |
write | 创建和更新 |
delete | 删除数据 |
admin | 管理功能 |
申请权限
在 OAuth 授权时指定 scope:
const scope = 'read write';
// 或
const scope = 'read write delete admin';
安全最佳实践
保护 API 密钥
- 不要暴露在前端代码中
- 使用环境变量存储
- 定期轮换密钥
- 使用不同的密钥区分不同应用
环境变量示例
# .env 文件(不要提交到版本控制)
OPENHUMAN_API_KEY=your_secret_key
密钥轮换
定期更换 API 密钥:
- 创建新密钥
- 更新所有使用旧密钥的应用
- 验证新密钥正常工作
- 撤销旧密钥