Sample code for 30+ languages & platforms
PureBasic 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 PureBasic Downloads

PureBasic
IncludeFile "CkJsonObject.pb"
IncludeFile "CkOAuth2.pb"
IncludeFile "CkDateTime.pb"

Procedure ChilkatExample()

    success.i = 0

    ;  Assumes Chilkat is unlocked. See Global Unlock Sample.

    oauth.i = CkOAuth2::ckCreate()
    If oauth.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkOAuth2::setCkTokenEndpoint(oauth, "https://login.microsoftonline.com/common/oauth2/v2.0/token")
    CkOAuth2::setCkClientId(oauth, "CLIENT_ID")
    ;  A public desktop client does not have a client secret.

    CkOAuth2::setCkAuthorizationEndpoint(oauth, "https://login.microsoftonline.com/common/oauth2/v2.0/authorize")
    CkOAuth2::setCkLocalHost(oauth, "localhost")
    CkOAuth2::setCkListenPort(oauth, 3017)
    CkOAuth2::setCkCodeChallenge(oauth, 1)
    CkOAuth2::setCkCodeChallengeMethod(oauth, "S256")
    ;  Request only the protocols your application needs; this sample covers all three.
    CkOAuth2::setCkScope(oauth, "offline_access https://outlook.office.com/SMTP.Send https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/POP.AccessAsUser.All")
    success = CkOAuth2::ckAddAuthQueryParam(oauth,"prompt","select_account")
    If success <> 1
        Debug "Could not configure account selection."
        CkOAuth2::ckDispose(oauth)
        ProcedureReturn
    EndIf

    authUrl.s = CkOAuth2::ckStartAuth(oauth)
    If CkOAuth2::ckLastMethodSuccess(oauth) <> 1
        Debug "Could not start the loopback listener."
        CkOAuth2::ckDispose(oauth)
        ProcedureReturn
    EndIf

    success = CkOAuth2::ckLaunchBrowser(oauth,authUrl)
    If success <> 1
        CkOAuth2::ckCancel(oauth)
        Debug "Could not open the system browser."
        CkOAuth2::ckDispose(oauth)
        ProcedureReturn
    EndIf

    waited.i = 0
    While ((CkOAuth2::ckAuthFlowState(oauth) < 3) AND (waited < 180000))
        CkOAuth2::ckSleepMs(oauth,200)
        waited = waited + 200
    Wend
    If CkOAuth2::ckAuthFlowState(oauth) < 3
        CkOAuth2::ckCancel(oauth)
        Debug "Authorization timed out."
        CkOAuth2::ckDispose(oauth)
        ProcedureReturn
    EndIf

    If CkOAuth2::ckAuthFlowState(oauth) <> 3
        Debug "Authorization did not complete. Flow state: " + Str(CkOAuth2::ckAuthFlowState(oauth))
        CkOAuth2::ckDispose(oauth)
        ProcedureReturn
    EndIf

    token.i = CkJsonObject::ckCreate()
    If token.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkJsonObject::ckLoad(token,CkOAuth2::ckAccessTokenResponse(oauth))
    If success <> 1
        Debug "Could not parse the token response."
        CkOAuth2::ckDispose(oauth)
        CkJsonObject::ckDispose(token)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(token,"refresh_token") <> 1) OR (CkJsonObject::ckStringOfEquals(token,"refresh_token","",1) = 1)
        Debug "No offline refresh token was issued. The existing cache was preserved."
        CkOAuth2::ckDispose(oauth)
        CkJsonObject::ckDispose(token)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(token,"access_token") <> 1) OR (CkJsonObject::ckStringOfEquals(token,"access_token","",1) = 1)
        Debug "The response did not contain an access token. The existing cache was preserved."
        CkOAuth2::ckDispose(oauth)
        CkJsonObject::ckDispose(token)
        ProcedureReturn
    EndIf

    obtained.i = CkDateTime::ckCreate()
    If obtained.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkDateTime::ckSetFromCurrentSystemTime(obtained)
    CkJsonObject::ckUpdateString(token,"obtained_at",CkDateTime::ckGetAsTimestamp(obtained,0))
    ;  The token response includes expires_in (seconds). Refresh before the access token expires.
    ;  The file contains credentials: use a private, access-controlled directory.
    success = CkJsonObject::ckWriteFile(token,"qa_data/tokens/office365.json")
    If success <> 1
        Debug "Could not save the token file."
        CkOAuth2::ckDispose(oauth)
        CkJsonObject::ckDispose(token)
        CkDateTime::ckDispose(obtained)
        ProcedureReturn
    EndIf

    Debug "Credentials saved in the private working directory."


    CkOAuth2::ckDispose(oauth)
    CkJsonObject::ckDispose(token)
    CkDateTime::ckDispose(obtained)


    ProcedureReturn
EndProcedure