JavaScript Requires Chilkat v11.0.0+
JavaScript
Refresh a Gmail OAuth access token
See more GMail REST API Examples
Use the refresh token and the same Desktop app client that issued it. Run in the private directory used by the authorization example. Preserve the refresh token if Google omits it from the response. Refreshing continues the existing grant. Request additional scopes through interactive authorization.
Note
This example is intended for running within a Chilkat.Js embedded JavaScript engine. All Chilkat JavaScript examples require Chilkat
v11.4.0 or greater.
var success = false;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
var token = new CkJsonObject();
success = token.LoadFile("gmail-token.json");
if (success !== true) {
console.log("Could not read gmail-token.json from the private working directory.");
return;
}
if ((token.JsonTypeOf("refresh_token") !== 1) || (token.StringOfEquals("refresh_token","",true) == true)) {
console.log("Authorize the account for offline access first.");
return;
}
var oauth = new CkOAuth2();
oauth.TokenEndpoint = "https://oauth2.googleapis.com/token";
oauth.ClientId = "YOUR_DESKTOP_CLIENT_ID";
oauth.ClientSecret = "YOUR_DESKTOP_CLIENT_SECRET";
oauth.RefreshToken = token.StringOf("refresh_token");
success = oauth.RefreshAccessToken();
if (success !== true) {
console.log("Refresh failed. Check the OAuth client and grant. A revoked or expired grant requires fresh consent.");
return;
}
var fresh = new CkJsonObject();
success = fresh.Load(oauth.AccessTokenResponse);
if (success !== true) {
console.log("Could not parse the refresh response.");
return;
}
if ((fresh.JsonTypeOf("access_token") !== 1) || (fresh.StringOfEquals("access_token","",true) == true)) {
console.log("The refresh response did not contain an access token.");
return;
}
if ((fresh.JsonTypeOf("refresh_token") !== 1) || (fresh.StringOfEquals("refresh_token","",true) == true)) {
fresh.UpdateString("refresh_token",token.StringOf("refresh_token"));
}
if ((fresh.HasMember("scope") !== true) && (token.JsonTypeOf("scope") == 1)) {
fresh.UpdateString("scope",token.StringOf("scope"));
}
success = fresh.WriteFile("gmail-token.json");
if (success !== true) {
console.log("Could not save the refreshed credentials.");
return;
}
console.log("Refreshed the access token.");