Sample code for 30+ languages & platforms
Node.js Requires Chilkat v11.6.0+

Outlook Calendar: Refresh a Delegated Access Token

See more Outlook Calendar Examples

Refresh the Graph token obtained by the public desktop PKCE example, without a client secret or browser. Use the same client ID and authority. This works after a user has signed in and consented; it is not app-only authentication. A refresh token is not permanent: invalid_grant or an interaction requirement means the user must authorize again.

Form parameters are encoded by Chilkat. HTTP/JSON/token-validation failures leave the old cache untouched. Save a new refresh token when one is returned; retain the previous one if the field is absent. A private backup protects against a replacement-write failure; production code should replace credentials atomically, serialize refreshes per account, and remove obsolete protected backups according to its retention policy. No credentials are printed.

The cache is qa_data/tokens/outlookCalendar.json. Refresh before its acquired-time plus expires_in lifetime has elapsed. Keep each 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 calendar data private.

Microsoft documentation

Chilkat Node.js Downloads

Node.js
NODEJS_PRELUDE

function chilkatExample() {

    var success = false;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = false;
    var token = new chilkat.JsonObject();
    token.Strict = true;
    success = token.LoadFile("qa_data/tokens/outlookCalendar.json");
    if (success !== true) {
        console.log("Read the private token cache or authorize again.");
        return;
    }

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

    var clientId = "YOUR_APPLICATION_CLIENT_ID";
    //  Use the same app and authority as the original authorization.
    var tokenUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
    var http = new chilkat.Http();
    http.RequireSslCertVerify = true;
    http.FollowRedirects = false;
    http.ConnectTimeout = 20;
    http.ReadTimeout = 30;
    var req = new chilkat.HttpRequest();
    req.HttpVerb = "POST";
    req.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.
    var resp = new chilkat.HttpResponse();
    var result = new chilkat.JsonObject();
    result.Strict = true;
    success = http.HttpReq(tokenUrl,req,resp);
    //  A false result can still include an HTTP error response.
    if ((success !== true) && (resp.StatusCode == 0)) {
        console.log("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.");
        return;
    }

    if (resp.StatusCode !== 200) {
        console.log("Unexpected HTTP status: " + resp.StatusCode);
        console.log("Request ID: " + resp.GetHeaderField("request-id"));
        if (resp.StatusCode == 429) {
            console.log("Retry-After: " + resp.GetHeaderField("Retry-After"));
        }

        if (resp.StatusCode == 401) {
            console.log("Refresh the Graph access token or authorize again.");
        }

        return;
    }

    success = result.Load(resp.BodyStr);
    if (success !== true) {
        console.log("Expected a well-formed JSON response.");
        return;
    }

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

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

    }

    var obtained = new chilkat.CkDateTime();
    success = obtained.SetFromCurrentSystemTime();
    if (success !== true) {
        console.log("Could not timestamp the refreshed token.");
        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/outlookCalendar.json.bak");
    if (success !== true) {
        console.log("Could not back up the old cache; no replacement attempted.");
        return;
    }

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

    console.log("Refreshed the calendar token cache.");

}

chilkatExample();