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

Microsoft 365: Obtain Mail OAuth2 Tokens with Desktop PKCE

See more Office365 Examples

Obtain delegated SMTP, IMAP, and POP access with authorization code flow and S256 PKCE. Register a public desktop application in Microsoft Entra with a Mobile and desktop applications loopback redirect URI of http://localhost:3017/. Do not register this callback as a Web or SPA application. No client secret belongs in a distributed desktop application. Run the sample where the user can launch a browser and return to the local listener; it is not a web-server callback example.

The common authority supports work/school and personal accounts only if the app registration supports those account types. For a single-tenant work/school app, replace common in both endpoints with the mailbox tenant ID. The account needs an Exchange Online mailbox; administrator consent or Conditional Access can restrict authorization.

The example requests all three delegated protocol permissions for demonstration. Remove unused scopes in your application. Microsoft Graph scopes and ID tokens are not substitutes for mail-protocol access tokens. The user may need consent again after revocation or policy changes; refresh is not guaranteed indefinitely.

Create qa_data/tokens in a private, access-controlled working directory before running. The saved JSON contains credentials, not just settings. Use separate caches per account, app, and authority; prevent concurrent writers, use an OS credential store in production, and never publish token responses. The sample validates the response before writing, but a production cache also needs atomic replacement and recovery from write failures.

Microsoft reference documentation

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkOAuth2W.h>
#include <CkJsonObjectW.h>
#include <CkDateTimeW.h>

void ChilkatSample(void)
    {
    bool success = false;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.

    CkOAuth2W oauth;
    oauth.put_TokenEndpoint(L"https://login.microsoftonline.com/common/oauth2/v2.0/token");
    oauth.put_ClientId(L"CLIENT_ID");
    //  A public desktop client does not have a client secret.

    oauth.put_AuthorizationEndpoint(L"https://login.microsoftonline.com/common/oauth2/v2.0/authorize");
    oauth.put_LocalHost(L"localhost");
    oauth.put_ListenPort(3017);
    oauth.put_CodeChallenge(true);
    oauth.put_CodeChallengeMethod(L"S256");
    //  Request only the protocols your application needs; this sample covers all three.
    oauth.put_Scope(L"offline_access https://outlook.office.com/SMTP.Send https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/POP.AccessAsUser.All");
    success = oauth.AddAuthQueryParam(L"prompt",L"select_account");
    if (success != true) {
        wprintf(L"Could not configure account selection.\n");
        return;
    }

    const wchar_t *authUrl = oauth.startAuth();
    if (oauth.get_LastMethodSuccess() != true) {
        wprintf(L"Could not start the loopback listener.\n");
        return;
    }

    success = oauth.LaunchBrowser(authUrl);
    if (success != true) {
        oauth.Cancel();
        wprintf(L"Could not open the system browser.\n");
        return;
    }

    int waited = 0;
    while (((oauth.get_AuthFlowState() < 3) && (waited < 180000))) {
        oauth.SleepMs(200);
        waited = waited + 200;
    }

    if (oauth.get_AuthFlowState() < 3) {
        oauth.Cancel();
        wprintf(L"Authorization timed out.\n");
        return;
    }

    if (oauth.get_AuthFlowState() != 3) {
        wprintf(L"Authorization did not complete. Flow state: %d\n",oauth.get_AuthFlowState());
        return;
    }

    CkJsonObjectW token;
    success = token.Load(oauth.accessTokenResponse());
    if (success != true) {
        wprintf(L"Could not parse the token response.\n");
        return;
    }

    if ((token.JsonTypeOf(L"refresh_token") != 1) || (token.StringOfEquals(L"refresh_token",L"",true) == true)) {
        wprintf(L"No offline refresh token was issued. The existing cache was preserved.\n");
        return;
    }

    if ((token.JsonTypeOf(L"access_token") != 1) || (token.StringOfEquals(L"access_token",L"",true) == true)) {
        wprintf(L"The response did not contain an access token. The existing cache was preserved.\n");
        return;
    }

    CkDateTimeW obtained;
    obtained.SetFromCurrentSystemTime();
    token.UpdateString(L"obtained_at",obtained.getAsTimestamp(false));
    //  The token response includes expires_in (seconds). Refresh before the access token expires.
    //  The file contains credentials: use a private, access-controlled directory.
    success = token.WriteFile(L"qa_data/tokens/office365.json");
    if (success != true) {
        wprintf(L"Could not save the token file.\n");
        return;
    }

    wprintf(L"Credentials saved in the private working directory.\n");
    }