Dart Requires Chilkat v11.0.0+
Dart
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.
Chilkat Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
// Assumes Chilkat is unlocked. See Global Unlock Sample.
final token = CkJsonObject();
try {
token.loadFile('gmail-token.json');
} on ChilkatException {
print('Could not read gmail-token.json from the private working directory.');
return;
}
if ((token.jsonTypeOf('refresh_token') != 1) || (token.stringOfEquals('refresh_token', '', true))) {
print('Authorize the account for offline access first.');
return;
}
final oauth = 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');
try {
oauth.refreshAccessToken();
} on ChilkatException {
print('Refresh failed. Check the OAuth client and grant. A revoked or expired grant requires fresh consent.');
return;
}
final fresh = CkJsonObject();
try {
fresh.load(oauth.accessTokenResponse);
} on ChilkatException {
print('Could not parse the refresh response.');
return;
}
if ((fresh.jsonTypeOf('access_token') != 1) || (fresh.stringOfEquals('access_token', '', true))) {
print('The refresh response did not contain an access token.');
return;
}
if ((fresh.jsonTypeOf('refresh_token') != 1) || (fresh.stringOfEquals('refresh_token', '', true))) {
fresh.updateString('refresh_token', token.stringOf('refresh_token'));
}
if ((!fresh.hasMember('scope')) && (token.jsonTypeOf('scope') == 1)) {
fresh.updateString('scope', token.stringOf('scope'));
}
try {
fresh.writeFile('gmail-token.json');
} on ChilkatException {
print('Could not save the refreshed credentials.');
return;
}
print('Refreshed the access token.');
}