What I have so far is the app redirects to the consent page. The user accepts, then I'm redirected back to localhost with a valid authorization code. From what I understand, I need to make another call and exchange this code for an access token. getAccessToken()
is not working, however. The console log is returning this:
invalid_client
invalid_request
Please let me know which additional information is needed.
Here's the relevant code:
var { google } = require('googleapis');
var http = require("http");
var request = require('request');
var oauth2Client = new google.auth.OAuth2(
'<My Client ID>',
'<My Client Secret>',
'http://localhost:8080'
);
exports.generateAuthCodeUrl = function () {
const url = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: 'https://www.googleapis.com/auth/blogger'
});
return url;
};
exports.getAccessToken = function (accessCode) {
var codeOptions = {
code: accessCode
}
oauth2Client.getToken(codeOptions, function (err, tokens) {
// Now tokens contains an access_token and an optional refresh_token. Save them.
if (!err) {
oauth2Client.setCredentials(tokens);
return tokens;
}
console.log(err.message);
});
};
Edit: Summary and what worked for me
I read the linked article from pinoyyid's answer TWICE and also noted the steps listed in his answer. Listing the simple steps helped me understand more clearly. Also, as recommended in the comments, I removed the googleapi library (The error mentioned above was occurring within the code of this library) and just made regular calls to the necessary endpoints with the request
library. I used request
because it's much less verbose. The code that I ended up with looks like this:
exports.generateAuthCodeUrl = function () {
var authURL = "https://accounts.google.com/o/oauth2/v2/auth?" +
"client_id=" + client_id +
"&scope=" + scope +
"&redirect_uri=" + redirect_uri +
"&response_type=" + response_type;
//redirect to consent page
return authURL;
};
exports.getAccessToken = function (x) {
var postDataUrl = 'https://www.googleapis.com/oauth2/v4/token?' +
'code=' + x + //auth code received from the previous call
'&client_id=' + client_id +
'&client_secret=' + client_secret +
'&redirect_uri=' + redirect_uri +
'&grant_type=' + "authorization_code"
var options = {
uri: postDataUrl,
method: 'POST'
};
request(options, function (err, res, body) {
return body; //returns an object with an access token!!!
});
};
Very glad I got this working!! Thank you all so much