![](/img/trans.png)
[英]Getting 401 Unauthorized error while requasting GitHub API
[英]Getting error 401 - unauthorized with google API
我正在嘗試訪問 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'
}
也許我以錯誤的方式發送令牌?
找到了解決辦法。 對於在調用 Play Developer API 時遇到問題的其他人 - 您只需將 makeApiRequest 函數替換為:
function makeApiRequest(url, accessToken) {
config = {
method: 'get',
url: url + `?access_token=${accessToken}`
};
return axios(config);
}
只需將 access_token 作為參數傳遞,我仍然不知道為什么它不能與 auth 屬性一起使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.