跳到主要内容

CloudBase 登录态长期保持方案

在使用腾讯云开发(CloudBase)进行用户认证时,Token 有效期较短,用户长时间不使用应用后需要重新登录。本文介绍如何使用 refresh token 机制实现登录态的长期保持。

问题现象​

使用云开发 HTTP API 进行用户认证时遇到以下问题:

  • Token 有效期较短,需要频繁刷新
  • 用户长时间(几天或几周)不使用应用后,Token 过期需要重新登录
  • 应用在后台无法触发 Token 刷新,导致用户体验不佳

解决方案​

云开发提供了 refresh token 机制,可以在主 Token 过期后通过 refresh token 自动获取新的访问 Token。

Refresh Token 机制说明​

Token 类型有效期用途
Access Token2 小时(7200 秒)访问云资源的凭证
Refresh Token默认 31 天(可配置)用于刷新 Access Token

使用方法​

1. 获取 Token(包含 refresh_token)​

首次登录时,调用 /auth/v1/token 接口获取 Token(以密码模式为例):

const envId = 'your-env-id'
const response = await fetch(`https://${envId}.ap-shanghai.tcb-api.tencentcloudapi.com/auth/v1/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
grant_type: 'password',
username: 'your-username',
password: 'your-password',
client_id: envId
})
})

const data = await response.json()
// 保存 access_token 和 refresh_token
const { access_token, refresh_token, expires_in } = data

2. 使用 Refresh Token 刷新登录态​

当 Access Token 过期时,使用 Refresh Token 获取新的 Token:

const envId = 'your-env-id'
const response = await fetch(`https://${envId}.ap-shanghai.tcb-api.tencentcloudapi.com/auth/v1/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
grant_type: 'refresh_token',
refresh_token: savedRefreshToken,
client_id: envId
})
})

const data = await response.json()
// 更新保存的 token(注意:原 refresh_token 使用后立即失效)
const { access_token, refresh_token, expires_in } = data

最佳实践​

  1. 安全存储 Token:将 refresh_token 存储在安全的位置(如 Keychain、EncryptedSharedPreferences)

  2. 自动刷新机制:在应用启动或从后台恢复时检查 Token 状态

async function ensureValidToken() {
const tokenExpiry = getTokenExpiry()

if (Date.now() >= tokenExpiry - 60000) { // 提前 1 分钟刷新
await refreshAccessToken()
}
}
  1. 错误处理:当 refresh_token 也过期时,引导用户重新登录
async function refreshAccessToken() {
try {
const response = await refreshToken()
if (response.error) {
// 错误格式: { error: 'invalid_grant', error_code: 4001, error_description: '...' }
if (response.error === 'invalid_grant') {
// refresh_token 无效或已过期,引导用户重新登录
navigateToLogin()
return
}
}
saveTokens(response)
} catch (error) {
console.error('Token 刷新失败', error)
}
}
  1. 应用恢复时刷新:在应用从后台恢复时检查并刷新 Token
// React Native 示例
import { AppState } from 'react-native'

AppState.addEventListener('change', (nextAppState) => {
if (nextAppState === 'active') {
ensureValidToken()
}
})

注意事项​

  1. Refresh Token 也有有效期(默认 31 天),过期后需要用户重新登录
  2. 重要:刷新 Token 时原 refresh_token 立即失效,必须保存并使用返回的新 refresh_token
  3. 不要在不安全的位置(如 localStorage)存储 refresh_token
  4. 建议在 Token 即将过期前主动刷新,而不是等到过期后再刷新
  5. 可在云开发平台/身份认证/Token修改 Refresh Token 有效期

相关文档​