Sample code for 30+ languages & platforms
Dart Requires Chilkat v11.6.0+

Outlook Calendar: Refresh a Delegated Access Token

See more Outlook Calendar Examples

Refresh the Graph token obtained by the public desktop PKCE example, without a client secret or browser. Use the same client ID and authority. This works after a user has signed in and consented; it is not app-only authentication. A refresh token is not permanent: invalid_grant or an interaction requirement means the user must authorize again.

Form parameters are encoded by Chilkat. HTTP/JSON/token-validation failures leave the old cache untouched. Save a new refresh token when one is returned; retain the previous one if the field is absent. A private backup protects against a replacement-write failure; production code should replace credentials atomically, serialize refreshes per account, and remove obsolete protected backups according to its retention policy. No credentials are printed.

The cache is qa_data/tokens/outlookCalendar.json. Refresh before its acquired-time plus expires_in lifetime has elapsed. Keep each cache associated with its original app and account.

HTTP methods can return false for an HTTP error as well as a connection failure. The code distinguishes those cases and checks the expected status before reading JSON. For 401, refresh the access token or authorize again; for 403, check permissions, mailbox access, and tenant policy. For 429, honor Retry-After before a bounded retry. Do not automatically repeat a write after an uncertain outcome. Keep detailed errors and calendar data private.

Microsoft documentation

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  var success = false;

  // Assumes Chilkat is unlocked. See Global Unlock Sample.
  success = false;
  final token = CkJsonObject();
  token.strict = true;
  try {
    token.loadFile('qa_data/tokens/outlookCalendar.json');
  } on ChilkatException {
    print('Read the private token cache or authorize again.');
    return;
  }

  if ((token.jsonTypeOf('refresh_token') != 1) || (token.stringOfEquals('refresh_token', '', true))) {
    print('Expected a nonempty refresh_token in the JSON.');
    return;
  }

  final clientId = 'YOUR_APPLICATION_CLIENT_ID';
  // Use the same app and authority as the original authorization.
  final tokenUrl = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
  final http = CkHttp();
  http.requireSslCertVerify = true;
  http.followRedirects = false;
  http.connectTimeout = 20;
  http.readTimeout = 30;
  final req = CkHttpRequest();
  req.httpVerb = 'POST';
  req.contentType = 'application/x-www-form-urlencoded';
  req.addParam('client_id', clientId);
  req.addParam('grant_type', 'refresh_token');
  req.addParam('refresh_token', token.stringOf('refresh_token'));
  // Omitting scope retains the original grant instead of requesting additional permissions.
  final resp = CkHttpResponse();
  final result = CkJsonObject();
  result.strict = true;
  success = true;
  try {
    http.httpReq(tokenUrl, req, resp);
  } on ChilkatException {
    success = false;
  }
  // A false result can still include an HTTP error response.
  if ((!success) && (resp.statusCode == 0)) {
    print('No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.');
    return;
  }

  if (resp.statusCode != 200) {
    print('Unexpected HTTP status: ${resp.statusCode}');
    print('Request ID: ${resp.getHeaderField('request-id')}');
    if (resp.statusCode == 429) {
      print('Retry-After: ${resp.getHeaderField('Retry-After')}');
    }

    if (resp.statusCode == 401) {
      print('Refresh the Graph access token or authorize again.');
    }

    return;
  }

  try {
    result.load(resp.bodyStr);
  } on ChilkatException {
    print('Expected a well-formed JSON response.');
    return;
  }

  if ((result.jsonTypeOf('access_token') != 1) || (result.stringOfEquals('access_token', '', true))) {
    print('Expected a nonempty access_token in the JSON.');
    return;
  }

  if ((result.jsonTypeOf('expires_in') != 2) || (result.intOf('expires_in') <= 0)) {
    print('Missing token lifetime; old cache unchanged.');
    return;
  }

  if (result.jsonTypeOf('refresh_token') == -1) {
    result.updateString('refresh_token', token.stringOf('refresh_token'));
  } else {
    if ((result.jsonTypeOf('refresh_token') != 1) || (result.stringOfEquals('refresh_token', '', true))) {
      print('Expected a nonempty refresh_token in the JSON.');
      return;
    }
  }

  final obtained = CkDateTime();
  try {
    obtained.setFromCurrentSystemTime();
  } on ChilkatException {
    print('Could not timestamp the refreshed token.');
    return;
  }

  result.updateString('obtained_at', obtained.getAsTimestamp(false));
  // Keep a valid previous cache for recovery if the replacement write fails.
  try {
    token.writeFile('qa_data/tokens/outlookCalendar.json.bak');
  } on ChilkatException {
    print('Could not back up the old cache; no replacement attempted.');
    return;
  }

  try {
    result.writeFile('qa_data/tokens/outlookCalendar.json');
  } on ChilkatException {
    print('Could not save the new token; recover the previous cache from the private .bak file.');
    return;
  }

  print('Refreshed the calendar token cache.');
}