我在 Google Cloud 上的 Node.JS 中有一个云函数,我需要向 Google 发出 GET 请求,并且需要一个身份验证令牌。使用
curl
您可以使用 $(gcloud auth application-default print-access-token)
生成一个。但这在云实例中不起作用,那么我如何生成一个呢?
部分功能:
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 historyRequest = await axios.get(`https://toolresults.googleapis.com/toolresults/v1beta3/projects/${projectID}/histories/${historyID}/executions/${executionID}/environments`, {
headers: {
'Authorization': `Bearer $(gcloud auth application-default print-access-token)`,
'X-Goog-User-Project': projectID
}
});
花了无数个小时后,我在自动完成建议中滚动时偶然发现了答案。 Google 有有关身份验证的文档,但没有提到 Cloud Functions 发出 API 请求所需的内容:
const {GoogleAuth} = require('google-auth-library');
const auth = new GoogleAuth();
const token = await auth.getAccessToken()
const historyRequest = await axios.get(
`https://toolresults.googleapis.com/toolresults/v1beta3/projects/${projectID}/histories/${historyID}/executions/${executionID}/environments`,
{
headers: {
'Authorization': `Bearer ${token}`,
'X-Goog-User-Project': projectID
}
});
这是我的谷歌身份验证的最终工作代码。与上面类似,但具有范围和凭据。要设置服务的凭据,请参阅此处
import {GoogleAuth} from 'google-auth-library';
const auth = new GoogleAuth({
scopes: "https://www.googleapis.com/auth/cloud-platform",
credentials: {
"private_key": process.env.PRIVATE_KEY!,
"client_email": process.env.ADMIN_EMAIL!
}
});
const token = await auth.getAccessToken()