如何在Node.js中程序化生成GCP Bearer/Access Token?
Node.js程序化生成Google Cloud Vertex API访问令牌的方法
1. 使用Google Cloud官方客户端库(推荐)
官方客户端库会自动处理令牌的缓存与过期刷新,无需手动维护,是最可靠的实现方式。
安装依赖
npm install google-auth-library axios
改造后的代码示例
const { GoogleAuth } = require('google-auth-library'); const axios = require('axios'); const fetchCaptionForImage = async (image) => { // 初始化认证客户端,自动适配本地/生产环境凭据 const auth = new GoogleAuth({ scopes: ['https://www.googleapis.com/auth/cloud-platform'] }); const client = await auth.getClient(); const accessToken = await client.getAccessToken(); // 替换为你的Vertex API端点 const uri = "https://[REGION]-aiplatform.googleapis.com/v1/projects/[PROJECT_ID]/locations/[REGION]/publishers/google/models/imagetext:predict"; const body = { instances: [ { image: { bytesBase64Encoded: image // 传入图片的base64编码字符串 } } ] }; try { const response = await axios.post(uri, body, { headers: { 'Authorization': `Bearer ${accessToken.token}`, 'Content-Type': 'application/json' } }); console.log(response.data.predictions); } catch (error) { console.error('请求失败:', error.response?.data || error.message); } };
环境适配说明
- 本地开发:自动使用
gcloud auth login后的默认账户凭据 - GCP生产环境(如Cloud Functions、GKE):自动使用服务账号默认凭据
- 非GCP生产环境:设置环境变量
GOOGLE_APPLICATION_CREDENTIALS指向服务账号密钥JSON文件路径即可
2. 基于服务账号密钥的手动实现(非GCP环境专用)
如果应用部署在非GCP环境,可直接指定服务账号密钥文件生成令牌:
代码示例
const { GoogleAuth } = require('google-auth-library'); const axios = require('axios'); const path = require('path'); const fetchCaptionForImage = async (image) => { // 指定服务账号密钥文件路径 const auth = new GoogleAuth({ keyFilename: path.join(__dirname, 'your-service-account-key.json'), scopes: ['https://www.googleapis.com/auth/cloud-platform'] }); const client = await auth.getClient(); const accessToken = await client.getAccessToken(); const uri = "https://[REGION]-aiplatform.googleapis.com/v1/projects/[PROJECT_ID]/locations/[REGION]/publishers/google/models/imagetext:predict"; const body = { instances: [ { image: { bytesBase64Encoded: image } } ] }; try { const response = await axios.post(uri, body, { headers: { 'Authorization': `Bearer ${accessToken.token}`, 'Content-Type': 'application/json' } }); console.log(response.data.predictions); } catch (error) { console.error('请求失败:', error.response?.data || error.message); } };
3. 手动调用OAuth2端点(不推荐)
若不想依赖官方库,可手动实现JWT签名与令牌请求,但需自行维护缓存和过期逻辑:
安装额外依赖
npm install axios jsonwebtoken fs path
代码示例
const axios = require('axios'); const jwt = require('jsonwebtoken'); const fs = require('fs'); const path = require('path'); // 缓存令牌及过期时间 let cachedToken = null; let tokenExpiry = 0; const getAccessToken = async () => { const now = Date.now(); // 令牌未过期则直接返回 if (cachedToken && now < tokenExpiry) { return cachedToken; } // 读取服务账号密钥 const serviceAccount = JSON.parse(fs.readFileSync(path.join(__dirname, 'your-service-account-key.json'), 'utf8')); // 生成JWT签名 const jwtToken = jwt.sign( { iss: serviceAccount.client_email, scope: 'https://www.googleapis.com/auth/cloud-platform', aud: 'https://oauth2.googleapis.com/token', exp: Math.floor(now / 1000) + 3600, // 1小时有效期 iat: Math.floor(now / 1000) }, serviceAccount.private_key, { algorithm: 'RS256' } ); // 请求获取访问令牌 const response = await axios.post('https://oauth2.googleapis.com/token', null, { params: { grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion: jwtToken } }); cachedToken = response.data.access_token; tokenExpiry = now + (response.data.expires_in * 1000) - 60000; // 提前1分钟刷新 return cachedToken; }; const fetchCaptionForImage = async (image) => { const accessToken = await getAccessToken(); const uri = "https://[REGION]-aiplatform.googleapis.com/v1/projects/[PROJECT_ID]/locations/[REGION]/publishers/google/models/imagetext:predict"; const body = { instances: [ { image: { bytesBase64Encoded: image } } ] }; try { const response = await axios.post(uri, body, { headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json' } }); console.log(response.data.predictions); } catch (error) { console.error('请求失败:', error.response?.data || error.message); } };
内容的提问来源于stack exchange,提问作者Anurag Dhote
相关产品推荐
相关产品推荐

