Reputation: 900
I'm trying to access google subscriptions api and I've been struggling with the error for a couple of days now. According to documentation here: https://developers.google.com/identity/protocols/oauth2/service-account#httprest I have to create a JWT token and then exchange it for access_token, which I successfully do. But when I try to use this token on subscriptions API I get response with 401. I'm working in Node.js environment:
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);
});
The error:
{
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'
}
Maybe I'm sending the token the wrong way?
Upvotes: 1
Views: 6916
Reputation: 900
Found the solution. For other people who have troubles calling Play Developer API - you just need to replace makeApiRequest function with this:
function makeApiRequest(url, accessToken) {
config = {
method: 'get',
url: url + `?access_token=${accessToken}`
};
return axios(config);
}
Just pass the access_token as parameter, I still don't know why it didn't work with auth attribute though.
Upvotes: 1