【发布时间】:2020-12-23 01:17:20
【问题描述】:
我正在尝试访问 google 订阅 api,但我已经为这个错误苦苦挣扎了几天。根据此处的文档:https://developers.google.com/identity/protocols/oauth2/service-account#httprest 我必须创建一个 JWT 令牌,然后将其交换为 access_token,我成功地做到了。但是当我尝试在订阅 API 上使用这个令牌时,我得到了 401 的响应。我在 Node.js 环境中工作:
const functions = require('firebase-functions');
const jwt = require('jsonwebtoken');
const keyData = require('./key.json'); // Path to your JSON key file
const axios = require('axios');
function getAccessToken(keyData) {
// Create a JSON Web Token for the Service Account linked to Play Store
const token = jwt.sign(
{ scope: 'https://www.googleapis.com/auth/androidpublisher' },
keyData.private_key,
{
algorithm: 'RS256',
expiresIn: '1h',
issuer: keyData.client_email,
subject: keyData.client_email,
audience: 'https://www.googleapis.com/oauth2/v4/token'
}
);
// Make a request to Google APIs OAuth backend to exchange it for an access token
// Returns a promise
config = {
method: 'post',
url: 'https://www.googleapis.com/oauth2/v4/token',
data: {
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: token
}
};
return axios(config);
}
function makeApiRequest(url, accessToken) {
config = {
method: 'get',
url: url,
auth: {
bearer: accessToken
}
};
return axios(config);
}
console.log("start");
purchaseToken = "token";
requestUrl = "https://androidpublisher.googleapis.com/androidpublisher/v3/applications/{package}/purchases/subscriptions/{id}/tokens/" + purchaseToken;
getAccessToken(keyData)
.then(response => {
console.log("access_token: " + response.data.access_token);
return makeApiRequest(requestUrl, response.data.access_token);
})
.then(response => {
// TODO: process the response, e.g. validate the purchase, set access claims to the user etc.
response.send(response);
return;
})
.catch(err => {
console.log(err);
});
错误:
{
code: 401,
message: 'Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.',
errors: [
{
message: 'Login Required.',
domain: 'global',
reason: 'required',
location: 'Authorization',
locationType: 'header'
}
],
status: 'UNAUTHENTICATED'
}
也许我以错误的方式发送令牌?
【问题讨论】:
标签: javascript node.js rest https google-api