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

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoOauth
    String sAuthUrl
    Integer iWaited
    Handle hoToken
    Handle hoObtained
    String sTemp1
    Integer iTemp1
    Boolean bTemp1

    Move False To iSuccess

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

    Get Create (RefClass(cComChilkatOAuth2)) To hoOauth
    If (Not(IsComObjectCreated(hoOauth))) Begin
        Send CreateComObject of hoOauth
    End
    Set ComTokenEndpoint Of hoOauth To "https://login.microsoftonline.com/common/oauth2/v2.0/token"
    Set ComClientId Of hoOauth To "CLIENT_ID"
    //  A public desktop client does not have a client secret.

    Set ComAuthorizationEndpoint Of hoOauth To "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
    Set ComLocalHost Of hoOauth To "localhost"
    Set ComListenPort Of hoOauth To 3017
    Set ComCodeChallenge Of hoOauth To True
    Set ComCodeChallengeMethod Of hoOauth To "S256"
    //  Request only the protocols your application needs; this sample covers all three.
    Set ComScope Of hoOauth To "offline_access https://outlook.office.com/SMTP.Send https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/POP.AccessAsUser.All"
    Get ComAddAuthQueryParam Of hoOauth "prompt" "select_account" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not configure account selection."
        Procedure_Return
    End

    Get ComStartAuth Of hoOauth To sAuthUrl
    Get ComLastMethodSuccess Of hoOauth To bTemp1
    If (bTemp1 <> True) Begin
        Showln "Could not start the loopback listener."
        Procedure_Return
    End

    Get ComLaunchBrowser Of hoOauth sAuthUrl To iSuccess
    If (iSuccess <> True) Begin
        Get ComCancel Of hoOauth To iSuccess
        Showln "Could not open the system browser."
        Procedure_Return
    End

    Move 0 To iWaited
    While (((ComAuthFlowState(hoOauth)) < 3) And (iWaited < 180000))
        Send ComSleepMs To hoOauth 200
        Move (iWaited + 200) To iWaited
    Loop

    Get ComAuthFlowState Of hoOauth To iTemp1
    If (iTemp1 < 3) Begin
        Get ComCancel Of hoOauth To iSuccess
        Showln "Authorization timed out."
        Procedure_Return
    End

    Get ComAuthFlowState Of hoOauth To iTemp1
    If (iTemp1 <> 3) Begin
        Get ComAuthFlowState Of hoOauth To iTemp1
        Showln "Authorization did not complete. Flow state: " iTemp1
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatJsonObject)) To hoToken
    If (Not(IsComObjectCreated(hoToken))) Begin
        Send CreateComObject of hoToken
    End
    Get ComAccessTokenResponse Of hoOauth To sTemp1
    Get ComLoad Of hoToken sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not parse the token response."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoToken "refresh_token" To iTemp1
    Get ComStringOfEquals Of hoToken "refresh_token" "" True To bTemp1
    If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
        Showln "No offline refresh token was issued. The existing cache was preserved."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoToken "access_token" To iTemp1
    Get ComStringOfEquals Of hoToken "access_token" "" True To bTemp1
    If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
        Showln "The response did not contain an access token. The existing cache was preserved."
        Procedure_Return
    End

    Get Create (RefClass(cComCkDateTime)) To hoObtained
    If (Not(IsComObjectCreated(hoObtained))) Begin
        Send CreateComObject of hoObtained
    End
    Get ComSetFromCurrentSystemTime Of hoObtained To iSuccess
    Get ComGetAsTimestamp Of hoObtained False To sTemp1
    Get ComUpdateString Of hoToken "obtained_at" sTemp1 To iSuccess
    //  The token response includes expires_in (seconds). Refresh before the access token expires.
    //  The file contains credentials: use a private, access-controlled directory.
    Get ComWriteFile Of hoToken "qa_data/tokens/office365.json" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not save the token file."
        Procedure_Return
    End

    Showln "Credentials saved in the private working directory."


End_Procedure