login required error, when fetching calendar listGoogle Calendar API - Error 401 Login RequiredAccessing a public calendar using Google API without requiring a user to log inRegistering Glass Timeline Notification with Nodetypescript getting error TS2304: cannot find name ' require'Wait for data from external API before making POST requestError: Missing title - google calendar create or updatenode use koa-jwt create token exceed set time still use ?YouTube API Error, Node.jsGoogle Calendar API - Deeper insight into calendar usage limits exceeded errorsHow to send github OAuth data to client?
Can a creature sustain itself by eating its own severed body parts?
Did Don Young threaten John Boehner with a 10 inch blade to the throat?
Does switching on an old games console without a cartridge damage it?
How do you structure large embedded projects?
Does a "melee spell attack" use my spellcasting ability, or my Strength?
Question about differential signals as input of an operational amplifier
How does mathematics work?
My current job follows "worst practices". How can I talk about my experience in an interview without giving off red flags?
Has Iron Man made any suit for underwater combat?
Quickest way to move a line in a text file before another line in a text file?
Considerations when providing money to only one child out of two
Langton's Ant Periodic Behavior
Can a warlock shoot multiple beams from the Eldritch Blast cantrip with only a single free hand?
Is there any direct train from LHR Airport to Newcastle Gateshead?
Meaning of 行かしてもらうから
What does a Nintendo Game Boy do when turned on without a game cartridge inserted?
Can a ring have no zero divisors while being non-commutative and having no unity?
Why is DC so, so, so Democratic?
Longest to Shortest tractates of Yerushalmi by daf
What is the metal bit in the front of this propeller spinner?
Found old paper shares of Motorola Inc that has since been broken up
Is it OK to accept a job opportunity while planning on not taking it?
What is the AI assistant for the Iron Man Rescue armor?
How old is the Italian word "malandrino"?
login required error, when fetching calendar list
Google Calendar API - Error 401 Login RequiredAccessing a public calendar using Google API without requiring a user to log inRegistering Glass Timeline Notification with Nodetypescript getting error TS2304: cannot find name ' require'Wait for data from external API before making POST requestError: Missing title - google calendar create or updatenode use koa-jwt create token exceed set time still use ?YouTube API Error, Node.jsGoogle Calendar API - Deeper insight into calendar usage limits exceeded errorsHow to send github OAuth data to client?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I am trying to fetch the primary calendar in my nodeJS application, but its giving
login required error
code: 401,
errors:
[ domain: 'global',
reason: 'required',
message: 'Login Required',
locationType: 'header',
location: 'Authorization' ] }
following is the code
calendar.middleware.js
const google = require('googleapis');
const oAuth2Client = new google.auth.OAuth2(
CLIENT_ID,
CLIENT_SECRET,
'http://localhost:8000/api/v1/google/callback' //YOUR_REDIRECT_URL
);
const SCOPES = [
'https://www.googleapis.com/auth/calendar'
];
const authUrl = oAuth2Client.generateAuthUrl(
access_type: 'offline',
scope: SCOPES,
);
module.exports =
fetchToken: async function(req, res, next)
console.log("fetchToken");
const code = req.query.code;
try
const token = await oAuth2Client.getToken(code);
req.token = token;
next();
catch(e)
next(e);
,
fetchCalendars: async function(req, res, next)
console.log("fetchCalendars");
const token = req.token;
let cals;
oAuth2Client.setCredentials(token);
try
const calendar = await google.calendar(version: 'v3', oAuth2Client);
cals = calendar.calendarList.get(calendarId: 'primary');
console.log(cals);
next();
catch(e)
next(e);
routes/index.js
...
router.route('api/v1/google/callback').get( calendarMiddleware.fetchToken,
calendarMiddleware.fetchCalendars,
calendarController.googleCallback);
...
node.js google-api google-calendar-api google-api-nodejs-client
add a comment |
I am trying to fetch the primary calendar in my nodeJS application, but its giving
login required error
code: 401,
errors:
[ domain: 'global',
reason: 'required',
message: 'Login Required',
locationType: 'header',
location: 'Authorization' ] }
following is the code
calendar.middleware.js
const google = require('googleapis');
const oAuth2Client = new google.auth.OAuth2(
CLIENT_ID,
CLIENT_SECRET,
'http://localhost:8000/api/v1/google/callback' //YOUR_REDIRECT_URL
);
const SCOPES = [
'https://www.googleapis.com/auth/calendar'
];
const authUrl = oAuth2Client.generateAuthUrl(
access_type: 'offline',
scope: SCOPES,
);
module.exports =
fetchToken: async function(req, res, next)
console.log("fetchToken");
const code = req.query.code;
try
const token = await oAuth2Client.getToken(code);
req.token = token;
next();
catch(e)
next(e);
,
fetchCalendars: async function(req, res, next)
console.log("fetchCalendars");
const token = req.token;
let cals;
oAuth2Client.setCredentials(token);
try
const calendar = await google.calendar(version: 'v3', oAuth2Client);
cals = calendar.calendarList.get(calendarId: 'primary');
console.log(cals);
next();
catch(e)
next(e);
routes/index.js
...
router.route('api/v1/google/callback').get( calendarMiddleware.fetchToken,
calendarMiddleware.fetchCalendars,
calendarController.googleCallback);
...
node.js google-api google-calendar-api google-api-nodejs-client
add a comment |
I am trying to fetch the primary calendar in my nodeJS application, but its giving
login required error
code: 401,
errors:
[ domain: 'global',
reason: 'required',
message: 'Login Required',
locationType: 'header',
location: 'Authorization' ] }
following is the code
calendar.middleware.js
const google = require('googleapis');
const oAuth2Client = new google.auth.OAuth2(
CLIENT_ID,
CLIENT_SECRET,
'http://localhost:8000/api/v1/google/callback' //YOUR_REDIRECT_URL
);
const SCOPES = [
'https://www.googleapis.com/auth/calendar'
];
const authUrl = oAuth2Client.generateAuthUrl(
access_type: 'offline',
scope: SCOPES,
);
module.exports =
fetchToken: async function(req, res, next)
console.log("fetchToken");
const code = req.query.code;
try
const token = await oAuth2Client.getToken(code);
req.token = token;
next();
catch(e)
next(e);
,
fetchCalendars: async function(req, res, next)
console.log("fetchCalendars");
const token = req.token;
let cals;
oAuth2Client.setCredentials(token);
try
const calendar = await google.calendar(version: 'v3', oAuth2Client);
cals = calendar.calendarList.get(calendarId: 'primary');
console.log(cals);
next();
catch(e)
next(e);
routes/index.js
...
router.route('api/v1/google/callback').get( calendarMiddleware.fetchToken,
calendarMiddleware.fetchCalendars,
calendarController.googleCallback);
...
node.js google-api google-calendar-api google-api-nodejs-client
I am trying to fetch the primary calendar in my nodeJS application, but its giving
login required error
code: 401,
errors:
[ domain: 'global',
reason: 'required',
message: 'Login Required',
locationType: 'header',
location: 'Authorization' ] }
following is the code
calendar.middleware.js
const google = require('googleapis');
const oAuth2Client = new google.auth.OAuth2(
CLIENT_ID,
CLIENT_SECRET,
'http://localhost:8000/api/v1/google/callback' //YOUR_REDIRECT_URL
);
const SCOPES = [
'https://www.googleapis.com/auth/calendar'
];
const authUrl = oAuth2Client.generateAuthUrl(
access_type: 'offline',
scope: SCOPES,
);
module.exports =
fetchToken: async function(req, res, next)
console.log("fetchToken");
const code = req.query.code;
try
const token = await oAuth2Client.getToken(code);
req.token = token;
next();
catch(e)
next(e);
,
fetchCalendars: async function(req, res, next)
console.log("fetchCalendars");
const token = req.token;
let cals;
oAuth2Client.setCredentials(token);
try
const calendar = await google.calendar(version: 'v3', oAuth2Client);
cals = calendar.calendarList.get(calendarId: 'primary');
console.log(cals);
next();
catch(e)
next(e);
routes/index.js
...
router.route('api/v1/google/callback').get( calendarMiddleware.fetchToken,
calendarMiddleware.fetchCalendars,
calendarController.googleCallback);
...
node.js google-api google-calendar-api google-api-nodejs-client
node.js google-api google-calendar-api google-api-nodejs-client
edited Mar 26 at 13:40
DaImTo
49.8k12 gold badges78 silver badges265 bronze badges
49.8k12 gold badges78 silver badges265 bronze badges
asked Mar 26 at 13:24
Gopal ChavanGopal Chavan
125 bronze badges
125 bronze badges
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
'Login Required',
Means that you are not properly authenticating your request. The following should be close
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/calendar'];
// 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 Calendar API.
authorize(JSON.parse(content), fetchCalendars);
);
/**
* 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);
);
);
/**
* Lists the names and IDs of up to 10 files.
* @param google.auth.OAuth2 auth An authorized OAuth2 client.
*/
function fetchCalendars(auth)
const calendar = google.calendar(version: 'v3', auth);
cals = calendar.calendarList.get(calendarId: 'primary'), (err, res) =>
if (err) return console.log('The API returned an error: ' + err);
const items = res.items;
if (items.length)
console.log('Calendar:');
items.map((calendarList) =>
console.log(`$calendarList.description ($calendarList.id)`);
);
else
console.log('No files found.');
);
The code above is pieced together form Node.js quickstart Google drive Its the best auth example for node.js that i know of.
Thanks Dalm, basically I started with the same quickstart example you mentioned in above answer, but I wanted to use, async and await instead of promises, so I changed the quickStart code as per the requirement.
– Gopal Chavan
Apr 2 at 6:36
Your question is about login required error message i have answered that. I think you should open a new question about converting the code to use async await. someone else may be able to assist you with that
– DaImTo
Apr 2 at 6:46
I just now observed that, the token object i receved was not having refresh_token, do you have any idea why its not sending refresh token?
– Gopal Chavan
Apr 2 at 7:12
you need to request offline access if you have done that then have the user go to their google account and remove your access then request access again. Some scripting languages only return the refresh token the first time the user is authenticated. I think you can also use a promt force to force a reauth which may also return a refresh token.
– DaImTo
Apr 2 at 7:17
1
Thanks Dalm, I ended up following the same pattern you mentioned above, however i will open a new issue for converting the code to async await.
– Gopal Chavan
Apr 2 at 10:17
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55358296%2flogin-required-error-when-fetching-calendar-list%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
'Login Required',
Means that you are not properly authenticating your request. The following should be close
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/calendar'];
// 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 Calendar API.
authorize(JSON.parse(content), fetchCalendars);
);
/**
* 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);
);
);
/**
* Lists the names and IDs of up to 10 files.
* @param google.auth.OAuth2 auth An authorized OAuth2 client.
*/
function fetchCalendars(auth)
const calendar = google.calendar(version: 'v3', auth);
cals = calendar.calendarList.get(calendarId: 'primary'), (err, res) =>
if (err) return console.log('The API returned an error: ' + err);
const items = res.items;
if (items.length)
console.log('Calendar:');
items.map((calendarList) =>
console.log(`$calendarList.description ($calendarList.id)`);
);
else
console.log('No files found.');
);
The code above is pieced together form Node.js quickstart Google drive Its the best auth example for node.js that i know of.
Thanks Dalm, basically I started with the same quickstart example you mentioned in above answer, but I wanted to use, async and await instead of promises, so I changed the quickStart code as per the requirement.
– Gopal Chavan
Apr 2 at 6:36
Your question is about login required error message i have answered that. I think you should open a new question about converting the code to use async await. someone else may be able to assist you with that
– DaImTo
Apr 2 at 6:46
I just now observed that, the token object i receved was not having refresh_token, do you have any idea why its not sending refresh token?
– Gopal Chavan
Apr 2 at 7:12
you need to request offline access if you have done that then have the user go to their google account and remove your access then request access again. Some scripting languages only return the refresh token the first time the user is authenticated. I think you can also use a promt force to force a reauth which may also return a refresh token.
– DaImTo
Apr 2 at 7:17
1
Thanks Dalm, I ended up following the same pattern you mentioned above, however i will open a new issue for converting the code to async await.
– Gopal Chavan
Apr 2 at 10:17
add a comment |
'Login Required',
Means that you are not properly authenticating your request. The following should be close
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/calendar'];
// 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 Calendar API.
authorize(JSON.parse(content), fetchCalendars);
);
/**
* 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);
);
);
/**
* Lists the names and IDs of up to 10 files.
* @param google.auth.OAuth2 auth An authorized OAuth2 client.
*/
function fetchCalendars(auth)
const calendar = google.calendar(version: 'v3', auth);
cals = calendar.calendarList.get(calendarId: 'primary'), (err, res) =>
if (err) return console.log('The API returned an error: ' + err);
const items = res.items;
if (items.length)
console.log('Calendar:');
items.map((calendarList) =>
console.log(`$calendarList.description ($calendarList.id)`);
);
else
console.log('No files found.');
);
The code above is pieced together form Node.js quickstart Google drive Its the best auth example for node.js that i know of.
Thanks Dalm, basically I started with the same quickstart example you mentioned in above answer, but I wanted to use, async and await instead of promises, so I changed the quickStart code as per the requirement.
– Gopal Chavan
Apr 2 at 6:36
Your question is about login required error message i have answered that. I think you should open a new question about converting the code to use async await. someone else may be able to assist you with that
– DaImTo
Apr 2 at 6:46
I just now observed that, the token object i receved was not having refresh_token, do you have any idea why its not sending refresh token?
– Gopal Chavan
Apr 2 at 7:12
you need to request offline access if you have done that then have the user go to their google account and remove your access then request access again. Some scripting languages only return the refresh token the first time the user is authenticated. I think you can also use a promt force to force a reauth which may also return a refresh token.
– DaImTo
Apr 2 at 7:17
1
Thanks Dalm, I ended up following the same pattern you mentioned above, however i will open a new issue for converting the code to async await.
– Gopal Chavan
Apr 2 at 10:17
add a comment |
'Login Required',
Means that you are not properly authenticating your request. The following should be close
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/calendar'];
// 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 Calendar API.
authorize(JSON.parse(content), fetchCalendars);
);
/**
* 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);
);
);
/**
* Lists the names and IDs of up to 10 files.
* @param google.auth.OAuth2 auth An authorized OAuth2 client.
*/
function fetchCalendars(auth)
const calendar = google.calendar(version: 'v3', auth);
cals = calendar.calendarList.get(calendarId: 'primary'), (err, res) =>
if (err) return console.log('The API returned an error: ' + err);
const items = res.items;
if (items.length)
console.log('Calendar:');
items.map((calendarList) =>
console.log(`$calendarList.description ($calendarList.id)`);
);
else
console.log('No files found.');
);
The code above is pieced together form Node.js quickstart Google drive Its the best auth example for node.js that i know of.
'Login Required',
Means that you are not properly authenticating your request. The following should be close
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/calendar'];
// 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 Calendar API.
authorize(JSON.parse(content), fetchCalendars);
);
/**
* 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);
);
);
/**
* Lists the names and IDs of up to 10 files.
* @param google.auth.OAuth2 auth An authorized OAuth2 client.
*/
function fetchCalendars(auth)
const calendar = google.calendar(version: 'v3', auth);
cals = calendar.calendarList.get(calendarId: 'primary'), (err, res) =>
if (err) return console.log('The API returned an error: ' + err);
const items = res.items;
if (items.length)
console.log('Calendar:');
items.map((calendarList) =>
console.log(`$calendarList.description ($calendarList.id)`);
);
else
console.log('No files found.');
);
The code above is pieced together form Node.js quickstart Google drive Its the best auth example for node.js that i know of.
answered Mar 26 at 13:40
DaImToDaImTo
49.8k12 gold badges78 silver badges265 bronze badges
49.8k12 gold badges78 silver badges265 bronze badges
Thanks Dalm, basically I started with the same quickstart example you mentioned in above answer, but I wanted to use, async and await instead of promises, so I changed the quickStart code as per the requirement.
– Gopal Chavan
Apr 2 at 6:36
Your question is about login required error message i have answered that. I think you should open a new question about converting the code to use async await. someone else may be able to assist you with that
– DaImTo
Apr 2 at 6:46
I just now observed that, the token object i receved was not having refresh_token, do you have any idea why its not sending refresh token?
– Gopal Chavan
Apr 2 at 7:12
you need to request offline access if you have done that then have the user go to their google account and remove your access then request access again. Some scripting languages only return the refresh token the first time the user is authenticated. I think you can also use a promt force to force a reauth which may also return a refresh token.
– DaImTo
Apr 2 at 7:17
1
Thanks Dalm, I ended up following the same pattern you mentioned above, however i will open a new issue for converting the code to async await.
– Gopal Chavan
Apr 2 at 10:17
add a comment |
Thanks Dalm, basically I started with the same quickstart example you mentioned in above answer, but I wanted to use, async and await instead of promises, so I changed the quickStart code as per the requirement.
– Gopal Chavan
Apr 2 at 6:36
Your question is about login required error message i have answered that. I think you should open a new question about converting the code to use async await. someone else may be able to assist you with that
– DaImTo
Apr 2 at 6:46
I just now observed that, the token object i receved was not having refresh_token, do you have any idea why its not sending refresh token?
– Gopal Chavan
Apr 2 at 7:12
you need to request offline access if you have done that then have the user go to their google account and remove your access then request access again. Some scripting languages only return the refresh token the first time the user is authenticated. I think you can also use a promt force to force a reauth which may also return a refresh token.
– DaImTo
Apr 2 at 7:17
1
Thanks Dalm, I ended up following the same pattern you mentioned above, however i will open a new issue for converting the code to async await.
– Gopal Chavan
Apr 2 at 10:17
Thanks Dalm, basically I started with the same quickstart example you mentioned in above answer, but I wanted to use, async and await instead of promises, so I changed the quickStart code as per the requirement.
– Gopal Chavan
Apr 2 at 6:36
Thanks Dalm, basically I started with the same quickstart example you mentioned in above answer, but I wanted to use, async and await instead of promises, so I changed the quickStart code as per the requirement.
– Gopal Chavan
Apr 2 at 6:36
Your question is about login required error message i have answered that. I think you should open a new question about converting the code to use async await. someone else may be able to assist you with that
– DaImTo
Apr 2 at 6:46
Your question is about login required error message i have answered that. I think you should open a new question about converting the code to use async await. someone else may be able to assist you with that
– DaImTo
Apr 2 at 6:46
I just now observed that, the token object i receved was not having refresh_token, do you have any idea why its not sending refresh token?
– Gopal Chavan
Apr 2 at 7:12
I just now observed that, the token object i receved was not having refresh_token, do you have any idea why its not sending refresh token?
– Gopal Chavan
Apr 2 at 7:12
you need to request offline access if you have done that then have the user go to their google account and remove your access then request access again. Some scripting languages only return the refresh token the first time the user is authenticated. I think you can also use a promt force to force a reauth which may also return a refresh token.
– DaImTo
Apr 2 at 7:17
you need to request offline access if you have done that then have the user go to their google account and remove your access then request access again. Some scripting languages only return the refresh token the first time the user is authenticated. I think you can also use a promt force to force a reauth which may also return a refresh token.
– DaImTo
Apr 2 at 7:17
1
1
Thanks Dalm, I ended up following the same pattern you mentioned above, however i will open a new issue for converting the code to async await.
– Gopal Chavan
Apr 2 at 10:17
Thanks Dalm, I ended up following the same pattern you mentioned above, however i will open a new issue for converting the code to async await.
– Gopal Chavan
Apr 2 at 10:17
add a comment |
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55358296%2flogin-required-error-when-fetching-calendar-list%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown