Can Someone ELI5 How To Properly Do Offline Google Oauth2 With Node.js?
In the browser, I'm doing:
let { code } = await this.auth2.grantOfflineAccess();
I then save that code
in my DB.
Then on the server (node.js), I'm doing:
const { tokens } = await oauth2Client.getToken(code)
oauth2Client.setCredentials(tokens)
let { data } = await googleCalendar.calendarList.list({
auth: oauth2Client
})
The first time, tokens
has a refresh_token
. I save that as well. When I run this once, it works fine. When I run it again, it says the token is invalid. Somehow, I have to use the refresh_token
, to get a new token, but I don't know how. Can someone please explain like I'm 5?
Thanks
Answer
- You have already had the refresh token.
- You want to use the API with the access token refreshed by the refresh token.
- You want to achieve this using googleapis with Node.js.
If my understanding is correct, how about this answer? I think that the reason of your issue is that the authorization code can be used only one time. So it is required to retrieve the access token using the refresh token. In this answer, the access token is retrieved by the refresh token.
Modified script:
const refreshToken = "###"; // Please set your refresh token.
if (!refreshToken) { // Please modify this if statement for your situation.
const { tokens } = await oauth2Client.getToken(code);
oauth2Client.setCredentials(tokens);
} else {
oauth2Client.credentials = { refresh_token: refreshToken };
}
let { data } = await googleCalendar.calendarList.list({
auth: oauth2Client
});
Note:
- This modified script supposes that
oauth2Client
andgoogleCalendar
are declared. - When the refresh token is used, the authorization code is not required.
Reference:
If I misunderstood your question and this was not the result you want, I apologize.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM