Sample code for 30+ languages & platforms
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 C Downloads

C
#include <C_CkJsonObject.h>
#include <C_CkHttp.h>
#include <C_CkHttpRequest.h>
#include <C_CkHttpResponse.h>
#include <C_CkDateTime.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkJsonObject token;
    const char *clientId;
    const char *tokenUrl;
    HCkHttp http;
    HCkHttpRequest req;
    HCkHttpResponse resp;
    HCkJsonObject result;
    HCkDateTime obtained;

    success = FALSE;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = FALSE;
    token = CkJsonObject_Create();
    CkJsonObject_putStrict(token,TRUE);
    success = CkJsonObject_LoadFile(token,"qa_data/tokens/outlookContacts.json");
    if (success != TRUE) {
        printf("Read the private token cache or authorize again.\n");
        CkJsonObject_Dispose(token);
        return;
    }

    if ((CkJsonObject_JsonTypeOf(token,"refresh_token") != 1) || (CkJsonObject_StringOfEquals(token,"refresh_token","",TRUE) == TRUE)) {
        printf("Expected a nonempty refresh_token in the JSON.\n");
        CkJsonObject_Dispose(token);
        return;
    }

    clientId = "YOUR_APPLICATION_CLIENT_ID";
    //  Use the same app and authority as the original authorization.
    tokenUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
    http = CkHttp_Create();
    CkHttp_putRequireSslCertVerify(http,TRUE);
    CkHttp_putFollowRedirects(http,FALSE);
    CkHttp_putConnectTimeout(http,20);
    CkHttp_putReadTimeout(http,30);
    req = CkHttpRequest_Create();
    CkHttpRequest_putHttpVerb(req,"POST");
    CkHttpRequest_putContentType(req,"application/x-www-form-urlencoded");
    CkHttpRequest_AddParam(req,"client_id",clientId);
    CkHttpRequest_AddParam(req,"grant_type","refresh_token");
    CkHttpRequest_AddParam(req,"refresh_token",CkJsonObject_stringOf(token,"refresh_token"));
    //  Omitting scope retains the original grant instead of requesting additional permissions.
    resp = CkHttpResponse_Create();
    result = CkJsonObject_Create();
    CkJsonObject_putStrict(result,TRUE);
    success = CkHttp_HttpReq(http,tokenUrl,req,resp);
    //  A false result can still include an HTTP error response.
    if ((success != TRUE) && (CkHttpResponse_getStatusCode(resp) == 0)) {
        printf("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.\n");
        CkJsonObject_Dispose(token);
        CkHttp_Dispose(http);
        CkHttpRequest_Dispose(req);
        CkHttpResponse_Dispose(resp);
        CkJsonObject_Dispose(result);
        return;
    }

    if (CkHttpResponse_getStatusCode(resp) != 200) {
        printf("Unexpected HTTP status: %d\n",CkHttpResponse_getStatusCode(resp));
        printf("Request ID: %s\n",CkHttpResponse_getHeaderField(resp,"request-id"));
        if (CkHttpResponse_getStatusCode(resp) == 429) {
            printf("Retry-After: %s\n",CkHttpResponse_getHeaderField(resp,"Retry-After"));
        }

        if (CkHttpResponse_getStatusCode(resp) == 401) {
            printf("Refresh the Graph access token or authorize again.\n");
        }

        CkJsonObject_Dispose(token);
        CkHttp_Dispose(http);
        CkHttpRequest_Dispose(req);
        CkHttpResponse_Dispose(resp);
        CkJsonObject_Dispose(result);
        return;
    }

    success = CkJsonObject_Load(result,CkHttpResponse_bodyStr(resp));
    if (success != TRUE) {
        printf("Expected a well-formed JSON response.\n");
        CkJsonObject_Dispose(token);
        CkHttp_Dispose(http);
        CkHttpRequest_Dispose(req);
        CkHttpResponse_Dispose(resp);
        CkJsonObject_Dispose(result);
        return;
    }

    if ((CkJsonObject_JsonTypeOf(result,"access_token") != 1) || (CkJsonObject_StringOfEquals(result,"access_token","",TRUE) == TRUE)) {
        printf("Expected a nonempty access_token in the JSON.\n");
        CkJsonObject_Dispose(token);
        CkHttp_Dispose(http);
        CkHttpRequest_Dispose(req);
        CkHttpResponse_Dispose(resp);
        CkJsonObject_Dispose(result);
        return;
    }

    if ((CkJsonObject_JsonTypeOf(result,"expires_in") != 2) || (CkJsonObject_IntOf(result,"expires_in") <= 0)) {
        printf("Missing token lifetime; old cache unchanged.\n");
        CkJsonObject_Dispose(token);
        CkHttp_Dispose(http);
        CkHttpRequest_Dispose(req);
        CkHttpResponse_Dispose(resp);
        CkJsonObject_Dispose(result);
        return;
    }

    if (CkJsonObject_JsonTypeOf(result,"refresh_token") == -1) {
        CkJsonObject_UpdateString(result,"refresh_token",CkJsonObject_stringOf(token,"refresh_token"));
    }
    else {
        if ((CkJsonObject_JsonTypeOf(result,"refresh_token") != 1) || (CkJsonObject_StringOfEquals(result,"refresh_token","",TRUE) == TRUE)) {
            printf("Expected a nonempty refresh_token in the JSON.\n");
            CkJsonObject_Dispose(token);
            CkHttp_Dispose(http);
            CkHttpRequest_Dispose(req);
            CkHttpResponse_Dispose(resp);
            CkJsonObject_Dispose(result);
            return;
        }

    }

    obtained = CkDateTime_Create();
    success = CkDateTime_SetFromCurrentSystemTime(obtained);
    if (success != TRUE) {
        printf("Could not timestamp the refreshed token.\n");
        CkJsonObject_Dispose(token);
        CkHttp_Dispose(http);
        CkHttpRequest_Dispose(req);
        CkHttpResponse_Dispose(resp);
        CkJsonObject_Dispose(result);
        CkDateTime_Dispose(obtained);
        return;
    }

    CkJsonObject_UpdateString(result,"obtained_at",CkDateTime_getAsTimestamp(obtained,FALSE));
    //  Keep a valid previous cache for recovery if the replacement write fails.
    success = CkJsonObject_WriteFile(token,"qa_data/tokens/outlookContacts.json.bak");
    if (success != TRUE) {
        printf("Could not back up the old cache; no replacement attempted.\n");
        CkJsonObject_Dispose(token);
        CkHttp_Dispose(http);
        CkHttpRequest_Dispose(req);
        CkHttpResponse_Dispose(resp);
        CkJsonObject_Dispose(result);
        CkDateTime_Dispose(obtained);
        return;
    }

    success = CkJsonObject_WriteFile(result,"qa_data/tokens/outlookContacts.json");
    if (success != TRUE) {
        printf("Could not save the new token; recover the previous cache from the private .bak file.\n");
        CkJsonObject_Dispose(token);
        CkHttp_Dispose(http);
        CkHttpRequest_Dispose(req);
        CkHttpResponse_Dispose(resp);
        CkJsonObject_Dispose(result);
        CkDateTime_Dispose(obtained);
        return;
    }

    printf("Refreshed the contacts token cache.\n");


    CkJsonObject_Dispose(token);
    CkHttp_Dispose(http);
    CkHttpRequest_Dispose(req);
    CkHttpResponse_Dispose(resp);
    CkJsonObject_Dispose(result);
    CkDateTime_Dispose(obtained);

    }