如何在Node.js编写的Google Cloud Function中获取access token?
问题原因
你当前的实现存在两个核心问题:
$(gcloud auth application-default print-access-token)是Shell的命令替换语法,写在Node.js字符串中不会被执行,只会作为普通文本传递到请求头,完全无法生成有效令牌。- Google Cloud Functions运行环境默认没有预装gcloud CLI,即使你通过Node.js子进程调用该命令也无法正常运行。
解决方案
使用Google官方提供的google-auth-library库自动读取云函数运行环境的默认服务账号凭证,生成合法访问令牌,操作步骤如下:
- 安装依赖包
npm install google-auth-library
- 改造云函数代码
// 顶部引入认证库 const { GoogleAuth } = require('google-auth-library'); const auth = new GoogleAuth({ // 配置访问API所需的权限范围 scopes: 'https://www.googleapis.com/auth/cloud-platform' }); exports.postTestResultsToSlack = functions.testLab .testMatrix() .onComplete(async testMatrix => { if (testMatrix.clientInfo.details['testType'] != 'regression') { // Not regression tests return null; } const { testMatrixId, outcomeSummary, resultStorage } = testMatrix; const projectID = "project-feat1" const executionID = resultStorage.toolResultsExecutionId const historyID = resultStorage.toolResultsHistoryId // 新增:获取有效访问令牌 const client = await auth.getClient(); const accessToken = await client.getAccessToken(); const historyRequest = await axios.get(`https://toolresults.googleapis.com/toolresults/v1beta3/projects/${projectID}/histories/${historyID}/executions/${executionID}/environments`, { headers: { 'Authorization': `Bearer ${accessToken}`, 'X-Goog-User-Project': projectID } }); // 剩余原有逻辑 });
额外注意事项
- 需确保云函数绑定的默认服务账号(格式为
你的项目ID@appspot.gserviceaccount.com)拥有Tool Results API的访问权限,在IAM后台给该账号授予Tool Results Viewer角色即可。 - 该方案同时兼容本地调试场景,会自动读取你本地的application-default凭证,和你之前用gcloud生成令牌的逻辑完全兼容。
内容的提问来源于stack exchange,提问作者George
相关产品推荐
相关产品推荐

