node.js - Nodejs google oAuth2 invalid credentials -
i have following piece of code allows user create google calendar events. check if user has access token set, if not initiate regular oauth2 authorisation process , + save access token , refresh token inside user profile. subsequent request allow user create calendar events via access token set in profile.
here code:
function getnewtoken() { const authurl = oauth2client.generateauthurl({ access_type: 'offline', scope: scopes }); return authurl; } module.exports = { insert(req, res, next) { user.findbyid(req.user._id, (err, user) => { if (user.accesstoken) { oauth2client.setcredentials({ refresh_token: user.refreshtoken }); const calendar = google.calendar('v3'); calendar.events.quickadd({ auth: oauth2client, calendarid: 'primary', text: 'test calendar' }, (err, data) => { if (err) { next(err); } res.status(200).send('successfully added calendar event'); }); } else { const authurl = getnewtoken(); res.redirect(authurl); } }); }, googleoauth2callback(req, res, next) { const code = req.query.code; oauth2client.gettoken(code, (err, token) => { if (err) { next(err); } user.findbyidandupdate({ _id: req.user._id }, { accesstoken: token.access_token, refreshtoken: token.refresh_token }, (err) => { if (err) { next(err); } }); res.send({ token }); }); } };
however, i've noticed after time passes, "401 invalid credentials" error. i've noticed if omit access_token , set refresh token in oauth2client works expected.
is right way handle oauth2 tokens? can continue using refresh token in api requests? happens when refresh token expires? appreciated.
is right way handle oauth2 tokens?
from understand, yes. tokens short-lived , replaced new 1 once access has been made.
access tokens have limited lifetimes. if application needs access google api beyond lifetime of single access token, can obtain refresh token. refresh token allows application obtain new access tokens.
can continue using refresh token in api requests?
you can continue use tokens if part of scope.
access tokens valid set of operations , resources described in scope of token request. example, if access token issued google+ api, not grant access google contacts api. can, however, send access token google+ api multiple times similar operations.
what happens when refresh token expires?
once access tokens expire, application uses refresh token obtain new one.
in general, diagram identity documentation illustrates process fully.
for more information oauth2 in client-side application, check out web apps section of documentation.
Comments
Post a Comment