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

Outlook Calendar: Access a Microsoft 365 Calendar with a Certificate

See more Outlook Calendar Examples

Obtain an app-only Graph token using a signed certificate assertion, then read an explicitly named Microsoft 365 mailbox's default calendar. Upload the public certificate to the Entra app registration and keep its RSA private key private. Grant the appropriate Graph application permission and administrator consent: Calendars.ReadBasic for this read, or a stronger permission only for the operations required. Scope mailbox access using your organization's supported Exchange application-access controls/RBAC; avoid unintended tenant-wide access.

Private outlook-calendar-app.json contains tenant_id (the directory ID), client_id (Application ID), mailbox (object ID or UPN), pfx_path, and pfx_password. Use an organization tenant, not common/consumers. This is not available for personal Outlook.com mailboxes. Certificate authentication is not a requirement to run a public web server, but the private key must remain in a trusted application environment.

The short-lived assertion uses PS256 and an x5t#S256 thumbprint of the certificate's DER bytes. It is a credential submitted only to the token endpoint, not the Graph bearer token. Client credentials returns no refresh token: obtain another access token with a fresh assertion when needed. The example never prints tokens or assertions.

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 Unicode C++ Downloads

Unicode C++
#include <CkJsonObjectW.h>
#include <CkHttpW.h>
#include <CkStringBuilderW.h>
#include <CkCertW.h>
#include <CkPrivateKeyW.h>
#include <CkBinDataW.h>
#include <CkCrypt2W.h>
#include <CkDateTimeW.h>
#include <CkJwtW.h>
#include <CkHttpRequestW.h>
#include <CkHttpResponseW.h>

void ChilkatSample(void)
    {
    bool success = false;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = false;
    CkJsonObjectW config;
    config.put_Strict(true);
    success = config.LoadFile(L"outlook-calendar-app.json");
    if (success != true) {
        wprintf(L"Could not load private app configuration.\n");
        return;
    }

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

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

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

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

    //  pfx_password may be empty for an unencrypted test PFX; protect the private key in production.
    CkHttpW http;
    http.put_RequireSslCertVerify(true);
    http.put_FollowRedirects(false);
    http.put_ConnectTimeout(20);
    http.put_ReadTimeout(30);
    CkStringBuilderW tokenEndpoint;
    tokenEndpoint.Append(L"https://login.microsoftonline.com/");
    tokenEndpoint.Append(http.urlEncode(config.stringOf(L"tenant_id")));
    tokenEndpoint.Append(L"/oauth2/v2.0/token");
    const wchar_t *tokenUrl = tokenEndpoint.getAsString();
    CkCertW cert;
    success = cert.LoadPfxFile(config.stringOf(L"pfx_path"),config.stringOf(L"pfx_password"));
    if (success != true) {
        wprintf(L"Could not load the application certificate.\n");
        return;
    }

    CkPrivateKeyW key;
    success = cert.GetPrivateKey(key);
    if (success != true) {
        wprintf(L"The certificate needs an accessible RSA private key.\n");
        return;
    }

    CkBinDataW der;
    success = cert.ExportCertDerBd(der);
    if (success != true) {
        wprintf(L"Could not read the certificate DER bytes.\n");
        return;
    }

    CkCrypt2W crypt;
    crypt.put_HashAlgorithm(L"sha256");
    crypt.put_EncodingMode(L"base64url");
    const wchar_t *thumbprint = crypt.hashBdENC(der);
    if (crypt.get_LastMethodSuccess() != true) {
        wprintf(L"Could not hash the certificate.\n");
        return;
    }

    CkJsonObjectW header;
    header.UpdateString(L"alg",L"PS256");
    header.UpdateString(L"typ",L"JWT");
    header.UpdateString(L"x5t#S256",thumbprint);
    CkJsonObjectW claims;
    claims.UpdateString(L"aud",tokenUrl);
    claims.UpdateString(L"iss",config.stringOf(L"client_id"));
    claims.UpdateString(L"sub",config.stringOf(L"client_id"));
    const wchar_t *assertionId = crypt.generateUuid();
    if (crypt.get_LastMethodSuccess() != true) {
        wprintf(L"Could not create the assertion ID.\n");
        return;
    }

    claims.UpdateString(L"jti",assertionId);
    CkDateTimeW clock;
    success = clock.SetFromCurrentSystemTime();
    if (success != true) {
        wprintf(L"Could not read the clock.\n");
        return;
    }

    //  Numeric dates are JSON numbers built from decimal strings, without converting timestamps to a platform-sized integer.
    claims.UpdateNumber(L"iat",clock.getAsUnixTimeStr(false));
    claims.UpdateNumber(L"nbf",clock.getAsUnixTimeStr(false));
    success = clock.AddSeconds(300);
    if (success != true) {
        wprintf(L"Could not set assertion expiry.\n");
        return;
    }

    claims.UpdateNumber(L"exp",clock.getAsUnixTimeStr(false));
    CkJwtW jwt;
    const wchar_t *assertion = jwt.createJwtPk(header.emit(),claims.emit(),key);
    if (jwt.get_LastMethodSuccess() != true) {
        wprintf(L"Could not sign the client assertion.\n");
        return;
    }

    CkHttpRequestW req;
    req.put_HttpVerb(L"POST");
    req.put_ContentType(L"application/x-www-form-urlencoded");
    req.AddParam(L"client_id",config.stringOf(L"client_id"));
    req.AddParam(L"grant_type",L"client_credentials");
    req.AddParam(L"scope",L"https://graph.microsoft.com/.default");
    req.AddParam(L"client_assertion_type",L"urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
    req.AddParam(L"client_assertion",assertion);
    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;
    }

    http.put_AuthToken(result.stringOf(L"access_token"));
    //  App-only tokens have no /me. Address the approved mailbox explicitly.
    CkStringBuilderW endpoint;
    endpoint.Append(L"https://graph.microsoft.com/v1.0/users/");
    endpoint.Append(http.urlEncode(config.stringOf(L"mailbox")));
    endpoint.Append(L"/calendar?$select=id,name,canEdit");
    success = http.HttpNoBody(L"GET",endpoint.getAsString(),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"id") != 1) || (result.StringOfEquals(L"id",L"",true) == true)) {
        wprintf(L"Expected a nonempty id in the JSON.\n");
        return;
    }

    wprintf(L"Calendar ID: %s\n",result.stringOf(L"id"));
    wprintf(L"Calendar name: %s\n",result.stringOf(L"name"));
    }