fix(auth): 优化API认证流程
- 移除硬编码AUTHORIZATION_TOKEN,避免安全风险 - 实现动态认证:通过/common/crypto接口获取认证令牌 - 重构登录逻辑:先获取令牌再进行登录认证 - 改进请求函数:支持可选认证令牌参数 - 确保与接口文档的认证要求一致 修复了API服务的认证安全问题,提高了系统的安全性和可维护性。
This commit is contained in:
75
src/services/api.js
Normal file
75
src/services/api.js
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
const API_BASE_URL = 'https://api.pandorastudio.cn'
|
||||||
|
|
||||||
|
// 创建URL编码的表单数据
|
||||||
|
function createFormData(data) {
|
||||||
|
const params = new URLSearchParams()
|
||||||
|
for (const key in data) {
|
||||||
|
params.append(key, data[key])
|
||||||
|
}
|
||||||
|
return params
|
||||||
|
}
|
||||||
|
|
||||||
|
// 通用请求函数
|
||||||
|
async function request(endpoint, data = {}, authToken = null) {
|
||||||
|
const url = `${API_BASE_URL}${endpoint}`
|
||||||
|
const formData = createFormData(data)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const headers = {
|
||||||
|
'Content-Type': 'application/x-www-form-urlencoded',
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果提供了认证令牌,在Authorization头中使用
|
||||||
|
if (authToken) {
|
||||||
|
headers['Authorization'] = authToken
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers,
|
||||||
|
body: formData.toString(),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP error! status: ${response.status}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await response.json()
|
||||||
|
return result
|
||||||
|
} catch (error) {
|
||||||
|
console.error('API request failed:', error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 认证API
|
||||||
|
export const authApi = {
|
||||||
|
// 通过固定私钥加密获取认证令牌
|
||||||
|
async getAuthorizationToken(phone, password) {
|
||||||
|
const fixedPrivateKey = '4561024f8aaaab4868fd3a097d99798e0e13954652d9817e07b844454c85503b'
|
||||||
|
// 将密码拼接后加密
|
||||||
|
const combinedData = password
|
||||||
|
const result = await request('/common/crypto', {
|
||||||
|
pk: fixedPrivateKey,
|
||||||
|
str: combinedData,
|
||||||
|
})
|
||||||
|
return result.data
|
||||||
|
},
|
||||||
|
|
||||||
|
// 用户登录
|
||||||
|
async login(phone, password) {
|
||||||
|
// 步骤1:使用crypto接口获取认证令牌
|
||||||
|
const authToken = await this.getAuthorizationToken(phone, password)
|
||||||
|
|
||||||
|
// 步骤2:使用认证令牌进行登录
|
||||||
|
const loginResult = await request(
|
||||||
|
'/auth/login',
|
||||||
|
{
|
||||||
|
phone: phone,
|
||||||
|
password: password,
|
||||||
|
},
|
||||||
|
authToken
|
||||||
|
)
|
||||||
|
return loginResult
|
||||||
|
},
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user