How to Refresh Token Using Google OAuth2 (Javascript/REST) - oauth-2.0

I'm trying to get a new token from Google OAuth2 but I keep getting this error:
Here is my code (I'm using Expo to build React Native apps):
const uri = 'https://oauth2.googleapis.com/token'
const headerr = {
'Content-Type': 'Content-Type: application/x-www-form-urlencoded'
}
const bodyy = {
"client_id": '******************',
"refresh_token": `${refreshToken}`,
"grant_type":"refresh_token",
"access_type":"offline"
}
const fitnesss = await fetch(uri, {
method: "POST",
headers: headerr,
body: JSON.stringify(bodyy)
});
fitnesss.json().then(res => {
console.log(res)
})
Does anyone know how to solve this?

unsupported grant type means that the grant type refresh token is not supported with the language you are using.
The reason for this is that JavaScript is client sided which would mean that you would need to have the refresh token in the code. Anyone who viewed the source in the browser would be able to see and use your refresh token.
To use refresh tokens use a server sided language. For example Node.js
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';
// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Drive API.
authorize(JSON.parse(content), listFiles);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id, client_secret, redirect_uris[0]);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getAccessToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
* #param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback for the authorized client.
*/
function getAccessToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error retrieving access token', err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) return console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}

Related

Getting 400 error code from Axios request while implementing token revocation flow for Apple Sign-In in Firebase

I am trying to implement the token revocation flow for Apple Sign-In in Firebase, following the instructions given in this GitHub repository: https://github.com/jooyoungho/apple-token-revoke-in-firebase. However, when I try to run the code to get the Refresh Token, I keep receiving a 400 error code from the Axios request.
Here's the code I'm trying to implement:
exports.getRefreshToken = functions.https.onRequest(async (request, response) => {
const axios = require('axios');
const qs = require('qs')
const code = request.query.code;
const client_secret = makeJWT();
let data = {
'code': code,
'client_id': clientId,
'client_secret': client_secret,
'grant_type': 'authorization_code'
}
return axios.post(`https://appleid.apple.com/auth/token`, qs.stringify(data), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
})
.then(async res => {
const refresh_token = res.data.refresh_token;
response.send(refresh_token);
})
.catch((error) => {
response.send(error);
functions.logger.log('Error getting refresh token', {error})
})
});
I am using the app bundleID for client_id
The authorizationCode in my app is formatted in this manner
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.x.xxxxx.xxxxxxxxxxxxxxxxxxxxxx
I am using #awesome-cordova-plugins/sign-in-with-apple to re auth the user right before getting the refresh token so the authCode should still be valid.
I figured out my main issue. I renamed the AuthKey_XXXX.p8 file do not do that. I have the cloud function working locally.

Does signing of the JWT require internet access?

JWT process is to sign JWT and use JWT to retrieve an access token. This access token is used to call Google APIs.
We use Google auth library to sign JWT. IS this signing process container locally or does it require internet access to another service to sign the JWT?
In order to see the flow for retrieving the access token using the service account, for example, when it sees the script for retrieving the access token using Javascript, the value of jwt can be created without the web access. But, when the access token is retrieved using the jwt, it is required to access the endpoint of Google like https://www.googleapis.com/oauth2/v4/token. Ref
The script for retrieving the access token using the service account is as follows.
const private_key = "###"; // private_key of JSON file retrieved by creating Service Account
const client_email = "###"; // client_email of JSON file retrieved by creating Service Account
const scopes = ["https://www.googleapis.com/auth/drive.readonly"]; // Scopes
const url = "https://www.googleapis.com/oauth2/v4/token";
const header = { alg: "RS256", typ: "JWT" };
const now = Math.floor(Date.now() / 1000);
const claim = {
iss: client_email,
scope: scopes.join(" "),
aud: url,
exp: (now + 3600).toString(),
iat: now.toString(),
};
const signature = btoa(JSON.stringify(header)) + "." + btoa(JSON.stringify(claim));
const sign = new JSEncrypt();
sign.setPrivateKey(private_key);
const jwt = signature + "." + sign.sign(signature, CryptoJS.SHA256, "sha256");
const params = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
assertion: jwt,
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
}),
};
const obj = await fetch(url, params).then((res) => res.json()).catch((err) => console.log(err));
console.log(obj);
Referencs:
Using OAuth 2.0 for Server to Server Applications
GetAccessTokenFromServiceAccount_js

How to get google oauth refresh token in the lambda function by configuring the account linking section in alexa developer console?

I have referred this link https://medium.com/coinmonks/link-your-amazon-alexa-skill-with-a-google-api-within-5-minutes-7e488dc43168 and used same configuration as stated.
I am able to get access token in the lambda function var accesstoken =handlerInput.requestEnvelope.context.System.user.accessToken;
How to get refresh token in the handlerinput event by configuring the alexa developer console account linking section?
I have tried enable/disable skill in companion app,Tested with simulator,Removing alexa skill from the google auto access and then allowing access.
LaunchRequestHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'LaunchRequest' || (handlerInput.requestEnvelope.request.type === 'IntentRequest' && handlerInput.requestEnvelope.request.intent.name === 'LaunchRequest');
},
async handle(handlerInput) {
console.log('LAUNCH REQUEST CALLED');
const speechText = 'Welcome!';
if (handlerInput.requestEnvelope.context.System.user.accessToken === undefined) {
console.log('ACCESS TOKEN NOT FOUND IN LAUNCH REQUEST');
return handlerInput.responseBuilder
.speak("ACCESS TOKEN NOT FOUND IN LAUNCH REQUEST")
.reprompt("ACCESS TOKEN NOT FOUND IN LAUNCH REQUEST")
.withLinkAccountCard()
.withShouldEndSession(true)
.getResponse();
}
const fs = require('fs');
const readline = require('readline');
const { google } = require('googleapis');
const SCOPES = ['https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile','https://www.googleapis.com/auth/plus.me','https://www.googleapis.com/auth/tasks.readonly','https://www.googleapis.com/auth/tasks'];
function authorize() {
return new Promise((resolve) => {
const client_secret = process.env.client_secret;
const client_id = process.env.client_id;
const redirect_uris = ['*******************************', '*******************************', '*******************************'];
const oAuth2Client = new google.auth.OAuth2(
client_id, client_secret, redirect_uris[0]);
console.log('access token found : ' + handlerInput.requestEnvelope.context.System.user.accessToken);
oAuth2Client.credentials = { "access_token": handlerInput.requestEnvelope.context.System.user.accessToken };
The refresh token is not exposed to the Skill by Alexa, in other words : there is no way for your skill code to get access to the refresh token, this is entirely managed by Alexa. Alexa will use the refresh token behind the scene to ask your Identity Provider (Google in your case) a fresh token when your customer will access your skill and the access token is about to expire.
This is explained in Alexa Account Linking documentation at https://developer.amazon.com/docs/account-linking/account-linking-for-custom-skills.html#choose-auth-type-overview

How do I update my google sheet in v4?

I am new in google sheets v4 and I just want to know how can I update my google sheet in v4. I am using Nodejs and following is the code sample link which I am using Method: spreadsheets.values.update
You can use the sample script of the link. In you case, combining Quickstart and the sample script may be useful for you. The sample script is as follows.
In this sample script, the text of sample text is imported to the cell a1 of Sheet1.
Sample script :
var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'sheets.googleapis.com-nodejs-quickstart.json';
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the
// Google Sheets API.
authorize(JSON.parse(content), valuesUpdate);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* #param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
/**
* Store token to disk be used in later program executions.
*
* #param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
function valuesUpdate(auth) {
var sheets = google.sheets('v4');
var request = {
// The ID of the spreadsheet to update.
spreadsheetId: 'my-spreadsheet-id', // TODO: Update placeholder value.
// The A1 notation of the values to update.
range: 'Sheet1!a1:a1', // TODO: Update placeholder value.
// How the input data should be interpreted.
valueInputOption: 'RAW', // TODO: Update placeholder value.
resource: {'values': [['sample text']]},
auth: auth,
};
sheets.spreadsheets.values.update(request, function(err, response) {
if (err) {
console.error(err);
return;
}
// TODO: Change code below to process the `response` object:
console.log(JSON.stringify(response, null, 2));
});
}
IMPORTANT :
Please modify my-spreadsheet-id to yours in above script.
This sample script supposes that the script of Quickstart works fine.
After run the script of Quickstart, please remove sheets.googleapis.com-nodejs-quickstart.json once, before run the above sample script. After remove the file, please run the above script. By this, the refresh token with the new scopes is retrieved and it is used for updating values.
If you want to use this script, please use googleapis v24 or less. Because the latest version doesn't work. Because the following error occurs, even if valueInputOption is set.
Error: 'valueInputOption' is required but not specified
I believe that this error will be modified in the near future.
If I misunderstand your question, I'm sorry.

Why is OAuth2 with Gmail Nodejs Nodemailer producing "Username and Password not accepted" error

OAuth2 is producing "Username and Password not accepted" error when try to send email with Gmail+ Nodejs+Nodemailer
Code - Nodejs - Nodemailer and xoauth2
var nodemailer = require("nodemailer");
var generator = require('xoauth2').createXOAuth2Generator({
user: "", // Your gmail address.
clientId: "",
clientSecret: "",
refreshToken: "",
});
// listen for token updates
// you probably want to store these to a db
generator.on('token', function(token){
console.log('New token for %s: %s', token.user, token.accessToken);
});
// login
var smtpTransport = nodemailer.createTransport({
service: 'gmail',
auth: {
xoauth2: generator
}
});
var mailOptions = {
to: "",
subject: 'Hello ', // Subject line
text: 'Hello world ', // plaintext body
html: '<b>Hello world </b>' // html body
};
smtpTransport.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
} else {
console.log('Message sent: ' + info.response);
}
smtpTransport.close();
});
issues:
I used Google OAuth2 playground to create the tokens, https://developers.google.com/oauthplayground/
It looks to grab a valid accessToken ok, using the refreshToken, (i.e. it prints the new access token on the screen.) No errors until it tries to send the email.
I added the optional accessToken: but got the same error. ( "Username and Password not accepted")
I am not 100% sure about the "username", the docs say it needs a "user" email address - I guess the email of the account that created to token, but is not 100% clear. I have tried several things and none worked.
I have searched the options on the gmail accounts, did not find anything that looks wrong.
Also, when I did this with Java, it needed the google userID rather than the email address, not sure why this is using the email address and the Java is using the UserId.
nodemailer fails with a "compose" scope
The problem was the "scope"
it fails with:
https://www.googleapis.com/auth/gmail.compose
but works ok if I use
https://mail.google.com/
Simply just do the following:
1- Get credentials.json file from here https://developers.google.com/gmail/api/quickstart/nodejs press enable the Gmail API and then choose Desktop app
2- Save this file somewhere along with your credentials file
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
// If modifying these scopes, delete token.json.
const SCOPES = ['https://mail.google.com'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';
// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
if(err){
return console.log('Error loading client secret file:', err);
}
// Authorize the client with credentials, then call the Gmail API.
authorize(JSON.parse(content), getAuth);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if(err){
return getNewToken(oAuth2Client, callback);
}
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
* #param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback for the authorized client.
*/
function getNewToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error retrieving access token', err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) return console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
function getAuth(auth){
}
3 - Run this file by typing in your terminal: node THIS_FILE.js
4- You'll have token.json file
5- take user information from credentials.json and token.json and fill them in the following function
const nodemailer = require('nodemailer');
const { google } = require("googleapis");
const OAuth2 = google.auth.OAuth2;
const email = 'gmail email'
const clientId = ''
const clientSecret = ''
const refresh = ''
const oauth2Client = new OAuth2(
clientId,
clientSecret,
);
oauth2Client.setCredentials({
refresh_token: refresh
});
const newAccessToken = oauth2Client.getAccessToken()
let transporter = nodemailer.createTransport(
{
service: 'Gmail',
auth: {
type: 'OAuth2',
user: email,
clientId: clientId,
clientSecret: clientSecret,
refreshToken: refresh,
accessToken: newAccessToken
}
},
{
// default message fields
// sender info
from: 'Firstname Lastname <your gmail email>'
}
);
const mailOptions = {
from: email,
to: "",
subject: "Node.js Email with Secure OAuth",
generateTextFromHTML: true,
html: "<b>test</b>"
};
transporter.sendMail(mailOptions, (error, response) => {
error ? console.log(error) : console.log(response);
transporter.close();
});
If your problem is the scopes, here is some help to fix
Tried to add this as an edit to the top answer but it was rejected, don't really know why this is off topic?
See the note here: https://nodemailer.com/smtp/oauth2/#troubleshooting
How to modify the scopes
The scopes are baked into the authorization step when you get your first refresh_token. If you are generating your refresh token via code (for example using the Node.js sample) then the revised scope needs to be set when you request your authUrl.
For the Node.js sample you need to modify SCOPES:
// If modifying these scopes, delete token.json.
-const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
+const SCOPES = ['https://mail.google.com'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
And then the call to oAuth2Client.generateAuthUrl will produce a url that will request authorization from the user to accept full access.
from the Node.js sample:
function getNewToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});

Resources