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 <CkJsonObject.h>
#include <CkHttp.h>
#include <CkHttpRequest.h>
#include <CkHttpResponse.h>
#include <CkDateTime.h>

void ChilkatSample(void)
    {
    bool success = false;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = false;
    CkJsonObject token;
    token.put_Strict(true);
    success = token.LoadFile("qa_data/tokens/outlookContacts.json");
    if (success != true) {
        std::cout << "Read the private token cache or authorize again." << "\r\n";
        return;
    }

    if ((token.JsonTypeOf("refresh_token") != 1) || (token.StringOfEquals("refresh_token","",true) == true)) {
        std::cout << "Expected a nonempty refresh_token in the JSON." << "\r\n";
        return;
    }

    const char *clientId = "YOUR_APPLICATION_CLIENT_ID";
    //  Use the same app and authority as the original authorization.
    const char *tokenUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
    CkHttp http;
    http.put_RequireSslCertVerify(true);
    http.put_FollowRedirects(false);
    http.put_ConnectTimeout(20);
    http.put_ReadTimeout(30);
    CkHttpRequest req;
    req.put_HttpVerb("POST");
    req.put_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.
    CkHttpResponse resp;
    CkJsonObject result;
    result.put_Strict(true);
    success = http.HttpReq(tokenUrl,req,resp);
    //  A false result can still include an HTTP error response.
    if ((success != true) && (resp.get_StatusCode() == 0)) {
        std::cout << "No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying." << "\r\n";
        return;
    }

    if (resp.get_StatusCode() != 200) {
        std::cout << "Unexpected HTTP status: " << resp.get_StatusCode() << "\r\n";
        std::cout << "Request ID: " << resp.getHeaderField("request-id") << "\r\n";
        if (resp.get_StatusCode() == 429) {
            std::cout << "Retry-After: " << resp.getHeaderField("Retry-After") << "\r\n";
        }

        if (resp.get_StatusCode() == 401) {
            std::cout << "Refresh the Graph access token or authorize again." << "\r\n";
        }

        return;
    }

    success = result.Load(resp.bodyStr());
    if (success != true) {
        std::cout << "Expected a well-formed JSON response." << "\r\n";
        return;
    }

    if ((result.JsonTypeOf("access_token") != 1) || (result.StringOfEquals("access_token","",true) == true)) {
        std::cout << "Expected a nonempty access_token in the JSON." << "\r\n";
        return;
    }

    if ((result.JsonTypeOf("expires_in") != 2) || (result.IntOf("expires_in") <= 0)) {
        std::cout << "Missing token lifetime; old cache unchanged." << "\r\n";
        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) == true)) {
            std::cout << "Expected a nonempty refresh_token in the JSON." << "\r\n";
            return;
        }

    }

    CkDateTime obtained;
    success = obtained.SetFromCurrentSystemTime();
    if (success != true) {
        std::cout << "Could not timestamp the refreshed token." << "\r\n";
        return;
    }

    result.UpdateString("obtained_at",obtained.getAsTimestamp(false));
    //  Keep a valid previous cache for recovery if the replacement write fails.
    success = token.WriteFile("qa_data/tokens/outlookContacts.json.bak");
    if (success != true) {
        std::cout << "Could not back up the old cache; no replacement attempted." << "\r\n";
        return;
    }

    success = result.WriteFile("qa_data/tokens/outlookContacts.json");
    if (success != true) {
        std::cout << "Could not save the new token; recover the previous cache from the private .bak file." << "\r\n";
        return;
    }

    std::cout << "Refreshed the contacts token cache." << "\r\n";
    }