获取用户的JWT身份认证信息后,在后续请求下列客户 API 的 Request Header 中增加如下 Header:
- Authorization: Bearer {jwt}
- X-TIMESTAMP: 当前时间戳
- X-NONCE: 随机生成的UUID
- X-APPID: 当前需要使用的 UOS APP 的 AppId
- X-NONCE-TOKEN: hexadecimal(sha256(appId + ":" + appSecret + ":" + X-TIMESTAMP + ":" + X-NONCE))
"Nonce Authorization"是一种身份验证机制,用于确保在通信中的请求是合法的。"Nonce" 是 "Number Used Once"(一次性数字)的缩写,是一个只能使用一次的随机或唯一值。Nonce 在身份验证中通常用于防止重放攻击。
C#
// C# 使用示例
using System.Security.Cryptography;
using System.Text;
class Program
{
static Dictionary<string, string> SetNonce(string appId, string appSecret, string jwt)
{
string nonce = Guid.NewGuid().ToString();
long timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
string signString = $"{appId}:{appSecret}:{timestamp}:{nonce}";
string token = BitConverter.ToString(SHA256.HashData(Encoding.UTF8.GetBytes(signString))).Replace("-", "").ToLower();
return new Dictionary<string, string>
{
{ "Authorization", $"Bearer {jwt}" },
{ "Content-Type", "application/json" },
{ "X-TIMESTAMP", timestamp.ToString() },
{ "X-NONCE", nonce },
{ "X-NONCE-TOKEN", token },
{ "X-APPID", appId }
};
}
static async Task Main(string[] args)
{
// 替换 jwt 为获取到的 jwt
var headers = SetNonce(appId, appSecret, jwt);
using var httpClient = new HttpClient();
foreach (var header in headers)
{
httpClient.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
}
// 替换 url 为你需要请求的 url
var response = await httpClient.GetAsync(url);
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
}Python
# Python 使用示例
import time
import uuid
import hashlib
import requests
def set_nonce(app_id, app_secret, jwt):
nonce = str(uuid.uuid4())
timestamp = int(time.time())
sign_string = f"{app_id}:{app_secret}:{timestamp}:{nonce}"
token = hashlib.sha256(sign_string.encode("utf-8")).hexdigest()
return {
"Authorization": f"Bearer {jwt}",
"Content-Type": "application/json",
"X-TIMESTAMP": str(timestamp),
"X-NONCE": nonce,
"X-NONCE-TOKEN": token,
"X-APPID": app_id
}
# 替换 jwt 为获取到的 jwt
headers = set_nonce(app_id, app_secret, jwt)
# 替换 url 为你需要请求的 url
response = requests.get(url, headers=headers)JavaScript
// JavaScript 使用示例
const axios = require('axios');
const crypto = require('crypto');
function setNonce(appId, appSecret, jwt) {
const nonce = crypto.randomUUID();
const timestamp = Math.floor(Date.now() / 1000);
const signString = `${appId}:${appSecret}:${timestamp}:${nonce}`;
const token = crypto.createHash('sha256').update(signString, 'utf8').digest('hex');
return {
'Authorization': `Bearer ${jwt}`,
'Content-Type': 'application/json',
'X-TIMESTAMP': String(timestamp),
'X-NONCE': nonce,
'X-NONCE-TOKEN': token,
'X-APPID': appId
};
}
// 替换 jwt 为获取到的 jwt
const headers = setNonce(appId, appSecret, jwt);
// 替换 url 为你需要请求的 url
const response = await axios.get(url, { headers });