身份验证
SMSBAT ChatHub API 使用基于 JWT 令牌的两级身份验证系统,包含公司令牌和运营商令牌。
身份验证流程
graph TD
A[Login Credentials] --> B[Get Company Token]
B --> C[Use Company Token]
C --> D[Get Operator Token]
D --> E[Use Operator Token]
E --> F[Validate Token]
公司令牌
公司令牌提供组织级别对 ChatHub API 的访问。
获取公司令牌
端点: POST /api/company/get-token
请求:
curl -X POST https://chatapi.smsbat.com/api/company/get-token \
-H "Content-Type: application/json" \
-d '{
"login": "your-company-login",
"password": "your-company-password"
}'
请求体:
{
"login": "string",
"password": "string"
}
响应:
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
响应是一个 JWT 令牌字符串。
使用公司令牌
在 API 请求中使用公司令牌,可通过以下两种方式之一:
方法 1:Authorization Header(推荐)
curl -X GET https://chatapi.smsbat.com/api/company/organization \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
方法 2:X-Authorization-Key Header
curl -X GET https://chatapi.smsbat.com/api/company/organization \
-H "X-Authorization-Key: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
运营商令牌
运营商令牌为组织内的各个运营商提供用户级别的访问权限。
获取运营商令牌
端点: POST /api/operator/get-token
请求:
curl -X POST https://chatapi.smsbat.com/api/operator/get-token \
-H "Authorization: Bearer {company-token}" \
-H "Content-Type: application/json" \
-d '{
"id": 123,
"expiresAt": "2025-12-31T23:59:59Z"
}'
请求体:
{
"id": 0,
"expiresAt": "2025-01-20T14:33:34.147Z"
}
参数:
| 参数 | 类型 | 必填 | 描述 |
|---|---|---|---|
id | integer | 是 | 操作员 ID |
expiresAt | string (ISO 8601) | 是 | 令牌过期日期和时间(从现在起最多 24 小时) |
重要: 令牌的最大生命周期为 24 小时。expiresAt 参数不能超过未来的 24 小时。
响应:
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJvcGVyYXRvcl9pZCI6MTIzLCJleHAiOjE3Mzc0MTI3OTl9.example_signature"
使用操作员令牌
在 API 请求中包含操作员令牌:
curl -X GET https://chatapi.smsbat.com/api/operator \
-H "Authorization: Bearer {operator-token}"
令牌验证
在使用之前验证令牌是否仍然有效。
端点: POST /api/operator/validate-token
请求:
curl -X POST https://chatapi.smsbat.com/api/operator/validate-token \
-H "Authorization: Bearer {company-token}" \
-H "Content-Type: application/json" \
-d '{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}'
请求体:
{
"token": "string"
}
响应(有效令牌):
{
"isValid": true,
"operatorId": 123,
"clientId": 0,
"expiresAt": "2025-12-31T23:59:59Z",
"error": null
}
响应(无效令牌):
{
"isValid": false,
"error": "Invalid token"
}
令牌过期
公司令牌
- API 中没有明确的过期时间
- 请联系您的客户经理了解令牌生命周期政策
- 定期轮换令牌以确保安全
操作员令牌
- 在请求令牌时设置过期时间(
expiresAt参数) - 使用前验证令牌
- 在过期前请求新令牌
实现示例
Python
import requests
from datetime import datetime, timedelta
class ChatHubAuth:
def __init__(self, base_url):
self.base_url = base_url
self.company_token = None
self.operator_tokens = {}
def get_company_token(self, login, password):
"""Get company authentication token"""
response = requests.post(
f"{self.base_url}/api/company/get-token",
json={"login": login, "password": password}
)
response.raise_for_status()
self.company_token = response.json()
return self.company_token
def get_operator_token(self, operator_id, expires_days=30):
"""Get operator token with expiration"""
expires_at = (
datetime.utcnow() + timedelta(days=expires_days)
).isoformat() + "Z"
response = requests.post(
f"{self.base_url}/api/operator/get-token",
headers={"Authorization": f"Bearer {self.company_token}"},
json={"id": operator_id, "expiresAt": expires_at}
)
response.raise_for_status()
token = response.json()
self.operator_tokens[operator_id] = token
return token
def validate_token(self, token):
"""Validate if token is still valid"""
response = requests.post(
f"{self.base_url}/api/operator/validate-token",
headers={"Authorization": f"Bearer {self.company_token}"},
json={"token": token}
)
response.raise_for_status()
return response.json()
# Usage
auth = ChatHubAuth("https://chatapi.smsbat.com")
# Get company token
company_token = auth.get_company_token("login", "password")
# Get operator token
operator_token = auth.get_operator_token(operator_id=123, expires_days=30)
# Validate token
is_valid = auth.validate_token(operator_token)
print(f"Token valid: {is_valid['valid']}")
JavaScript (Node.js)
const axios = require('axios');
class ChatHubAuth {
constructor(baseUrl) {
this.baseUrl = baseUrl;
this.companyToken = null;
this.operatorTokens = {};
}
async getCompanyToken(login, password) {
const response = await axios.post(
`${this.baseUrl}/api/company/get-token`,
{ login, password }
);
this.companyToken = response.data;
return this.companyToken;
}
async getOperatorToken(operatorId, expiresDays = 30) {
const expiresAt = new Date(
Date.now() + expiresDays * 24 * 60 * 60 * 1000
).toISOString();
const response = await axios.post(
`${this.baseUrl}/api/operator/get-token`,
{ id: operatorId, expiresAt },
{
headers: {
Authorization: `Bearer ${this.companyToken}`
}
}
);
const token = response.data;
this.operatorTokens[operatorId] = token;
return token;
}
async validateToken(token) {
const response = await axios.post(
`${this.baseUrl}/api/operator/validate-token`,
{ token },
{
headers: {
Authorization: `Bearer ${this.companyToken}`
}
}
);
return response.data;
}
}
// Usage
const auth = new ChatHubAuth('https://chatapi.smsbat.com');
async function authenticate() {
// Get company token
const companyToken = await auth.getCompanyToken('login', 'password');
// Get operator token
const operatorToken = await auth.getOperatorToken(123, 30);
// Validate token
const validation = await auth.validateToken(operatorToken);
console.log('Token valid:', validation.isValid);
}
authenticate();
PHP
<?php
class ChatHubAuth {
private $baseUrl;
private $companyToken;
private $operatorTokens = [];
public function __construct($baseUrl) {
$this->baseUrl = $baseUrl;
}
public function getCompanyToken($login, $password) {
$ch = curl_init($this->baseUrl . '/api/company/get-token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'login' => $login,
'password' => $password
]));
$response = curl_exec($ch);
curl_close($ch);
$this->companyToken = json_decode($response);
return $this->companyToken;
}
public function getOperatorToken($operatorId, $expiresDays = 30) {
$expiresAt = date(
'Y-m-d\TH:i:s\Z',
time() + ($expiresDays * 24 * 60 * 60)
);
$ch = curl_init($this->baseUrl . '/api/operator/get-token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $this->companyToken
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'id' => $operatorId,
'expiresAt' => $expiresAt
]));
$response = curl_exec($ch);
curl_close($ch);
$token = json_decode($response);
$this->operatorTokens[$operatorId] = $token;
return $token;
}
public function validateToken($token) {
$ch = curl_init($this->baseUrl . '/api/operator/validate-token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $this->companyToken
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'token' => $token
]));
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
}
// Usage
$auth = new ChatHubAuth('https://chatapi.smsbat.com');
// Get company token
$companyToken = $auth->getCompanyToken('login', 'password');
// Get operator token
$operatorToken = $auth->getOperatorToken(123, 30);
// Validate token
$validation = $auth->validateToken($operatorToken);
echo "Token valid: " . ($validation['isValid'] ? 'Yes' : 'No');
最佳实践
令牌存储
- ✅ 安全存储令牌(加密数据库,密钥管理器)
- ✅ 切勿将令牌提交到版本控制
- ✅ 使用环境变量存放凭证
- ❌ 不要以明文形式存储令牌
- ❌ 不要在客户端代码中暴露令牌
令牌轮换
- 定期轮换公司令牌(每 3-6 个月)
- 为操作员令牌设置合理的过期时间(7-30 天)
- 在过期前实现自动令牌刷新
- 当运营商离职时撤销令牌
错误处理
async function authenticateWithRetry(login, password, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
return await getCompanyToken(login, password);
} catch (error) {
if (error.response?.status === 401) {
throw new Error('Invalid credentials');
}
if (i === retries - 1) throw error;
// Wait before retry
await new Promise(resolve =>
setTimeout(resolve, Math.pow(2, i) * 1000)
);
}
}
}
令牌验证
在关键操作之前始终验证令牌:
async function performSecureOperation(token, operation) {
// Validate token first
const validation = await validateToken(token);
if (!validation.isValid) {
throw new Error('Token expired or invalid');
}
// Proceed with operation
return await operation();
}
安全注意事项
仅限 HTTPS
发送身份验证请求时始终使用 HTTPS:
// ✅ Correct
const baseUrl = 'https://chatapi.smsbat.com';
// ❌ Wrong - never use HTTP for authentication
const baseUrl = 'http://api.chathub.smsbat.com';
令牌范围
为每个操作使用适当的令牌:
- Company Token:组织管理,运营商创建
- Operator Token:聊天操作,消息处理
速率限制
对身份验证请求实施速率限制:
class RateLimitedAuth {
constructor() {
this.lastRequest = 0;
this.minInterval = 1000; // 1 second between requests
}
async getToken(login, password) {
const now = Date.now();
const timeSinceLastRequest = now - this.lastRequest;
if (timeSinceLastRequest < this.minInterval) {
await new Promise(resolve =>
setTimeout(resolve, this.minInterval - timeSinceLastRequest)
);
}
this.lastRequest = Date.now();
return await makeAuthRequest(login, password);
}
}
故障排除
401 未授权
- 验证凭据是否正确
- 检查令牌是否已过期
- 确保令牌已包含在请求头中
- 验证令牌格式
403 禁止
- 验证令牌具有所需的权限
- 检查是否使用了正确的令牌类型(company vs operator)
- 确保令牌未被撤销
令牌已过期
- 请求新令牌
- 实施自动令牌刷新
- 设置适当的过期时间
后续步骤
- Organizations - 管理组织
- Operators - 与运营商合作
- Widget Integration - 集成聊天小部件