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

Unicode C
#include <C_CkJsonObjectW.h>
#include <C_CkHttpW.h>
#include <C_CkHttpRequestW.h>
#include <C_CkHttpResponseW.h>
#include <C_CkDateTimeW.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkJsonObjectW token;
    const wchar_t *clientId;
    const wchar_t *tokenUrl;
    HCkHttpW http;
    HCkHttpRequestW req;
    HCkHttpResponseW resp;
    HCkJsonObjectW result;
    HCkDateTimeW obtained;

    success = FALSE;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = FALSE;
    token = CkJsonObjectW_Create();
    CkJsonObjectW_putStrict(token,TRUE);
    success = CkJsonObjectW_LoadFile(token,L"qa_data/tokens/outlookContacts.json");
    if (success != TRUE) {
        wprintf(L"Read the private token cache or authorize again.\n");
        CkJsonObjectW_Dispose(token);
        return;
    }

    if ((CkJsonObjectW_JsonTypeOf(token,L"refresh_token") != 1) || (CkJsonObjectW_StringOfEquals(token,L"refresh_token",L"",TRUE) == TRUE)) {
        wprintf(L"Expected a nonempty refresh_token in the JSON.\n");
        CkJsonObjectW_Dispose(token);
        return;
    }

    clientId = L"YOUR_APPLICATION_CLIENT_ID";
    //  Use the same app and authority as the original authorization.
    tokenUrl = L"https://login.microsoftonline.com/common/oauth2/v2.0/token";
    http = CkHttpW_Create();
    CkHttpW_putRequireSslCertVerify(http,TRUE);
    CkHttpW_putFollowRedirects(http,FALSE);
    CkHttpW_putConnectTimeout(http,20);
    CkHttpW_putReadTimeout(http,30);
    req = CkHttpRequestW_Create();
    CkHttpRequestW_putHttpVerb(req,L"POST");
    CkHttpRequestW_putContentType(req,L"application/x-www-form-urlencoded");
    CkHttpRequestW_AddParam(req,L"client_id",clientId);
    CkHttpRequestW_AddParam(req,L"grant_type",L"refresh_token");
    CkHttpRequestW_AddParam(req,L"refresh_token",CkJsonObjectW_stringOf(token,L"refresh_token"));
    //  Omitting scope retains the original grant instead of requesting additional permissions.
    resp = CkHttpResponseW_Create();
    result = CkJsonObjectW_Create();
    CkJsonObjectW_putStrict(result,TRUE);
    success = CkHttpW_HttpReq(http,tokenUrl,req,resp);
    //  A false result can still include an HTTP error response.
    if ((success != TRUE) && (CkHttpResponseW_getStatusCode(resp) == 0)) {
        wprintf(L"No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.\n");
        CkJsonObjectW_Dispose(token);
        CkHttpW_Dispose(http);
        CkHttpRequestW_Dispose(req);
        CkHttpResponseW_Dispose(resp);
        CkJsonObjectW_Dispose(result);
        return;
    }

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

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

        CkJsonObjectW_Dispose(token);
        CkHttpW_Dispose(http);
        CkHttpRequestW_Dispose(req);
        CkHttpResponseW_Dispose(resp);
        CkJsonObjectW_Dispose(result);
        return;
    }

    success = CkJsonObjectW_Load(result,CkHttpResponseW_bodyStr(resp));
    if (success != TRUE) {
        wprintf(L"Expected a well-formed JSON response.\n");
        CkJsonObjectW_Dispose(token);
        CkHttpW_Dispose(http);
        CkHttpRequestW_Dispose(req);
        CkHttpResponseW_Dispose(resp);
        CkJsonObjectW_Dispose(result);
        return;
    }

    if ((CkJsonObjectW_JsonTypeOf(result,L"access_token") != 1) || (CkJsonObjectW_StringOfEquals(result,L"access_token",L"",TRUE) == TRUE)) {
        wprintf(L"Expected a nonempty access_token in the JSON.\n");
        CkJsonObjectW_Dispose(token);
        CkHttpW_Dispose(http);
        CkHttpRequestW_Dispose(req);
        CkHttpResponseW_Dispose(resp);
        CkJsonObjectW_Dispose(result);
        return;
    }

    if ((CkJsonObjectW_JsonTypeOf(result,L"expires_in") != 2) || (CkJsonObjectW_IntOf(result,L"expires_in") <= 0)) {
        wprintf(L"Missing token lifetime; old cache unchanged.\n");
        CkJsonObjectW_Dispose(token);
        CkHttpW_Dispose(http);
        CkHttpRequestW_Dispose(req);
        CkHttpResponseW_Dispose(resp);
        CkJsonObjectW_Dispose(result);
        return;
    }

    if (CkJsonObjectW_JsonTypeOf(result,L"refresh_token") == -1) {
        CkJsonObjectW_UpdateString(result,L"refresh_token",CkJsonObjectW_stringOf(token,L"refresh_token"));
    }
    else {
        if ((CkJsonObjectW_JsonTypeOf(result,L"refresh_token") != 1) || (CkJsonObjectW_StringOfEquals(result,L"refresh_token",L"",TRUE) == TRUE)) {
            wprintf(L"Expected a nonempty refresh_token in the JSON.\n");
            CkJsonObjectW_Dispose(token);
            CkHttpW_Dispose(http);
            CkHttpRequestW_Dispose(req);
            CkHttpResponseW_Dispose(resp);
            CkJsonObjectW_Dispose(result);
            return;
        }

    }

    obtained = CkDateTimeW_Create();
    success = CkDateTimeW_SetFromCurrentSystemTime(obtained);
    if (success != TRUE) {
        wprintf(L"Could not timestamp the refreshed token.\n");
        CkJsonObjectW_Dispose(token);
        CkHttpW_Dispose(http);
        CkHttpRequestW_Dispose(req);
        CkHttpResponseW_Dispose(resp);
        CkJsonObjectW_Dispose(result);
        CkDateTimeW_Dispose(obtained);
        return;
    }

    CkJsonObjectW_UpdateString(result,L"obtained_at",CkDateTimeW_getAsTimestamp(obtained,FALSE));
    //  Keep a valid previous cache for recovery if the replacement write fails.
    success = CkJsonObjectW_WriteFile(token,L"qa_data/tokens/outlookContacts.json.bak");
    if (success != TRUE) {
        wprintf(L"Could not back up the old cache; no replacement attempted.\n");
        CkJsonObjectW_Dispose(token);
        CkHttpW_Dispose(http);
        CkHttpRequestW_Dispose(req);
        CkHttpResponseW_Dispose(resp);
        CkJsonObjectW_Dispose(result);
        CkDateTimeW_Dispose(obtained);
        return;
    }

    success = CkJsonObjectW_WriteFile(result,L"qa_data/tokens/outlookContacts.json");
    if (success != TRUE) {
        wprintf(L"Could not save the new token; recover the previous cache from the private .bak file.\n");
        CkJsonObjectW_Dispose(token);
        CkHttpW_Dispose(http);
        CkHttpRequestW_Dispose(req);
        CkHttpResponseW_Dispose(resp);
        CkJsonObjectW_Dispose(result);
        CkDateTimeW_Dispose(obtained);
        return;
    }

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


    CkJsonObjectW_Dispose(token);
    CkHttpW_Dispose(http);
    CkHttpRequestW_Dispose(req);
    CkHttpResponseW_Dispose(resp);
    CkJsonObjectW_Dispose(result);
    CkDateTimeW_Dispose(obtained);

    }