Sample code for 30+ languages & platforms
Objective-C Requires Chilkat v11.6.0+

Outlook Contacts: Refresh a Delegated Access Token

See more Outlook Contact Examples

After interactive authorization, refresh the Graph access token without reopening a browser. Use the same app client ID and authority as the contacts OAuth2 example. Omitting scope retains the original grant. This is delegated access, not application authentication; invalid_grant or an interaction requirement needs fresh interactive authorization.

The example validates the response, retains the previous refresh token when no replacement is returned, and saves a rotated token when present. HTTP or validation failures leave the old cache unchanged. A private backup protects against replacement-write failure; production applications should use protected atomic credential storage and serialize refreshes per account. Tokens are never printed.

Uses qa_data/tokens/outlookContacts.json. Refresh before the acquired time plus expires_in lifetime elapses. Keep the 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 contact data private.

Microsoft documentation

Chilkat Objective-C Downloads

Objective-C
#import <CkoJsonObject.h>
#import <NSString.h>
#import <CkoHttp.h>
#import <CkoHttpRequest.h>
#import <CkoHttpResponse.h>
#import <CkoDateTime.h>

BOOL success = NO;

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
success = NO;
CkoJsonObject *token = [[CkoJsonObject alloc] init];
token.Strict = YES;
success = [token LoadFile: @"qa_data/tokens/outlookContacts.json"];
if (success != YES) {
    NSLog(@"%@",@"Read the private token cache or authorize again.");
    return;
}

if (([[token JsonTypeOf: @"refresh_token"] intValue] != 1) || ([token StringOfEquals: @"refresh_token" value: @"" caseSensitive: YES] == YES)) {
    NSLog(@"%@",@"Expected a nonempty refresh_token in the JSON.");
    return;
}

NSString *clientId = @"YOUR_APPLICATION_CLIENT_ID";
//  Use the same app and authority as the original authorization.
NSString *tokenUrl = @"https://login.microsoftonline.com/common/oauth2/v2.0/token";
CkoHttp *http = [[CkoHttp alloc] init];
http.RequireSslCertVerify = YES;
http.FollowRedirects = NO;
http.ConnectTimeout = [NSNumber numberWithInt:20];
http.ReadTimeout = [NSNumber numberWithInt:30];
CkoHttpRequest *req = [[CkoHttpRequest alloc] init];
req.HttpVerb = @"POST";
req.ContentType = @"application/x-www-form-urlencoded";
[req AddParam: @"client_id" value: clientId];
[req AddParam: @"grant_type" value: @"refresh_token"];
[req AddParam: @"refresh_token" value: [token StringOf: @"refresh_token"]];
//  Omitting scope retains the original grant instead of requesting additional permissions.
CkoHttpResponse *resp = [[CkoHttpResponse alloc] init];
CkoJsonObject *result = [[CkoJsonObject alloc] init];
result.Strict = YES;
success = [http HttpReq: tokenUrl request: req response: resp];
//  A false result can still include an HTTP error response.
if ((success != YES) && ([resp.StatusCode intValue] == 0)) {
    NSLog(@"%@",@"No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.");
    return;
}

if ([resp.StatusCode intValue] != 200) {
    NSLog(@"%@%d",@"Unexpected HTTP status: ",[resp.StatusCode intValue]);
    NSLog(@"%@%@",@"Request ID: ",[resp GetHeaderField: @"request-id"]);
    if ([resp.StatusCode intValue] == 429) {
        NSLog(@"%@%@",@"Retry-After: ",[resp GetHeaderField: @"Retry-After"]);
    }

    if ([resp.StatusCode intValue] == 401) {
        NSLog(@"%@",@"Refresh the Graph access token or authorize again.");
    }

    return;
}

success = [result Load: resp.BodyStr];
if (success != YES) {
    NSLog(@"%@",@"Expected a well-formed JSON response.");
    return;
}

if (([[result JsonTypeOf: @"access_token"] intValue] != 1) || ([result StringOfEquals: @"access_token" value: @"" caseSensitive: YES] == YES)) {
    NSLog(@"%@",@"Expected a nonempty access_token in the JSON.");
    return;
}

if (([[result JsonTypeOf: @"expires_in"] intValue] != 2) || ([[result IntOf: @"expires_in"] intValue] <= 0)) {
    NSLog(@"%@",@"Missing token lifetime; old cache unchanged.");
    return;
}

if ([[result JsonTypeOf: @"refresh_token"] intValue] == -1) {
    [result UpdateString: @"refresh_token" value: [token StringOf: @"refresh_token"]];
}
else {
    if (([[result JsonTypeOf: @"refresh_token"] intValue] != 1) || ([result StringOfEquals: @"refresh_token" value: @"" caseSensitive: YES] == YES)) {
        NSLog(@"%@",@"Expected a nonempty refresh_token in the JSON.");
        return;
    }

}

CkoDateTime *obtained = [[CkoDateTime alloc] init];
success = [obtained SetFromCurrentSystemTime];
if (success != YES) {
    NSLog(@"%@",@"Could not timestamp the refreshed token.");
    return;
}

[result UpdateString: @"obtained_at" value: [obtained GetAsTimestamp: NO]];
//  Keep a valid previous cache for recovery if the replacement write fails.
success = [token WriteFile: @"qa_data/tokens/outlookContacts.json.bak"];
if (success != YES) {
    NSLog(@"%@",@"Could not back up the old cache; no replacement attempted.");
    return;
}

success = [result WriteFile: @"qa_data/tokens/outlookContacts.json"];
if (success != YES) {
    NSLog(@"%@",@"Could not save the new token; recover the previous cache from the private .bak file.");
    return;
}

NSLog(@"%@",@"Refreshed the contacts token cache.");