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

OneDrive: Refresh a Delegated Access Token

See more OneDrive Examples

Refresh the token from OneDrive authorization with PKCE, using the same application client ID and authority. This retains the user grant; it does not convert it to application access. Omitting scope retains the existing scopes. Obtain additional consent through authorization when needed.

The private oneDrive.json token cache is replaced only after a successful, validated response. Retain the previous refresh token when no replacement is returned, and save a rotated refresh token when supplied. A private backup is written first; production storage should use atomic replacement and a single refresh writer per account/application. invalid_grant or an interaction requirement requires sign-in again. Tokens and raw responses are not printed.

Permission: The original delegated grant.

Check the expected HTTP status before using a response body. A false method result can still contain an HTTP error response; status zero means no response arrived. For 401, renew authorization; for 403, check permissions, access grants, and policy; for 429, honor Retry-After with a bounded retry. Reconcile uncertain writes before repeating them. Keep credentials, file contents, upload/download URLs, and detailed diagnostics private.

Microsoft documentation

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkJsonObjectW.h>
#include <CkHttpW.h>
#include <CkHttpRequestW.h>
#include <CkHttpResponseW.h>
#include <CkDateTimeW.h>

void ChilkatSample(void)
    {
    bool success = false;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = false;
    CkJsonObjectW token;
    token.put_Strict(true);
    success = token.LoadFile(L"qa_data/tokens/oneDrive.json");
    if (success != true) {
        wprintf(L"Read the private token cache or authorize again.\n");
        return;
    }

    if ((token.JsonTypeOf(L"refresh_token") != 1) || (token.StringOfEquals(L"refresh_token",L"",true) == true)) {
        wprintf(L"Expected a nonempty refresh_token in the JSON.\n");
        return;
    }

    const wchar_t *clientId = L"YOUR_APPLICATION_CLIENT_ID";
    //  Use the same app and authority as the original authorization.
    const wchar_t *tokenUrl = L"https://login.microsoftonline.com/common/oauth2/v2.0/token";
    CkHttpW http;
    http.put_RequireSslCertVerify(true);
    http.put_FollowRedirects(false);
    http.put_ConnectTimeout(20);
    http.put_ReadTimeout(30);
    CkHttpRequestW req;
    req.put_HttpVerb(L"POST");
    req.put_ContentType(L"application/x-www-form-urlencoded");
    req.AddParam(L"client_id",clientId);
    req.AddParam(L"grant_type",L"refresh_token");
    req.AddParam(L"refresh_token",token.stringOf(L"refresh_token"));
    //  Omitting scope retains the original grant instead of requesting additional permissions.
    CkHttpResponseW resp;
    CkJsonObjectW 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)) {
        wprintf(L"No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.\n");
        return;
    }

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

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

        return;
    }

    success = result.Load(resp.bodyStr());
    if (success != true) {
        wprintf(L"Expected a well-formed JSON response.\n");
        return;
    }

    if ((result.JsonTypeOf(L"access_token") != 1) || (result.StringOfEquals(L"access_token",L"",true) == true)) {
        wprintf(L"Expected a nonempty access_token in the JSON.\n");
        return;
    }

    if ((result.JsonTypeOf(L"expires_in") != 2) || (result.IntOf(L"expires_in") <= 0)) {
        wprintf(L"Missing token lifetime; old cache unchanged.\n");
        return;
    }

    if (result.JsonTypeOf(L"refresh_token") == -1) {
        result.UpdateString(L"refresh_token",token.stringOf(L"refresh_token"));
    }
    else {
        if ((result.JsonTypeOf(L"refresh_token") != 1) || (result.StringOfEquals(L"refresh_token",L"",true) == true)) {
            wprintf(L"Expected a nonempty refresh_token in the JSON.\n");
            return;
        }

    }

    CkDateTimeW obtained;
    success = obtained.SetFromCurrentSystemTime();
    if (success != true) {
        wprintf(L"Could not timestamp the refreshed token.\n");
        return;
    }

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

    success = result.WriteFile(L"qa_data/tokens/oneDrive.json");
    if (success != true) {
        wprintf(L"Could not save the new token; recover the previous cache from the private .bak file.\n");
        return;
    }

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