我在获取正确的令牌来触发我的云功能时遇到问题。
通过 POSTMAN 测试时,我通过运行以下命令获取令牌:
gcloud auth print-identity-token
我的功能工作正常。
但在我的服务器上我使用以下代码。我也确实看到了该令牌,但我使用该令牌得到 401。
// Constants------------
const metadataServerTokenURL = 'http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience=';
async function gToken(){
let token='';
try{
// Fetch the token
const tokenResponse = await fetch(metadataServerTokenURL + 'https://'+process.env.CLOUD_URL, { //URL WITHOUT THE PATH
headers: {
'Metadata-Flavor': 'Google',
},
});
token = await tokenResponse.text();
} catch (err){
console.log(err);
}
return token;
}
- - - - -编辑 - - - -
调用函数::
app.get("/", async function(req , res){
try {
const token = await getToken();
console.log(`Token: ${token}`);
const functionResponse = await fetch('https://'+process.env.CLOUD_URL+process.env.PATH_TO_FUNC, {
method: 'post',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`},
});
console.log(`Status: ${await functionResponse.status}`);
res.sendStatus(200);
} catch (err){
console.log(err);
res.status(400).send('Something went wrong')
}
})
我的服务器是在 AppEngine 上运行的 NodeJS 代码。
请问我做错了什么?
----------EDIT 2--------------
I entered the two tokens received using two different ways, they show different information for some reason. Please see below::
Token from the server
Token using gcloud command locally (which works)::
服务器代码和云功能都托管在同一区域,并且属于同一项目的一部分。
process.env.CLOUD_URL > "e****-***2-c******-e******2.cloudfunctions.net"