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

Outlook Calendar: Authorize with OAuth2 and PKCE

See more Outlook Calendar Examples

Authorize an interactive desktop application using the Microsoft identity platform v2.0 authorization-code flow with PKCE (S256). This replaces the older public-client example that disabled PKCE, embedded a client secret, requested unrelated file/profile permissions, and printed tokens.

  1. Register an application in Microsoft Entra. Select personal Microsoft accounts, organizational accounts, or both according to the intended users. Copy the Application (client) ID, not the Object ID.
  2. Under Authentication, add a Mobile and desktop applications redirect URI of http://localhost:3017/. This is a local callback handled by Chilkat; it is not a hosted web-backend redirect.
  3. Add the delegated Microsoft Graph Calendars.ReadWrite permission for this example collection. A basic read-only application can instead use Calendars.ReadBasic; use Calendars.Read when fuller event information is required. Tenant consent policies can require an administrator even for delegated access.
  4. Use common only with the appropriate app account-type configuration, consumers for personal accounts only, organizations for organizational accounts, or your tenant ID for a single organization. Change both endpoints together.

offline_access requests a refresh token. Save the returned tokens privately and use the access token only for Graph. The saved obtained_at and expires_in describe its lifetime; refresh tokens can also expire or be revoked, so handle a need for interactive sign-in. This example saves a demonstration JSON cache; production applications should use protected credential storage and atomic replacement per account. No token is printed.

This system-browser/loopback example is intended for a machine with an interactive user. Web applications, mobile applications, and headless services need an authentication flow and redirect handling appropriate to their environment. Do not add a client secret to a public desktop application.

Microsoft documentation

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

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

    Move False To iSuccess

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    Move False To iSuccess
    Get Create (RefClass(cComChilkatOAuth2)) To hoOauth
    If (Not(IsComObjectCreated(hoOauth))) Begin
        Send CreateComObject of hoOauth
    End
    //  Register a Mobile and desktop applications redirect URI: http://localhost:3017/
    //  Use an account type that matches your app registration (common, consumers, or tenant ID).
    Set ComAuthorizationEndpoint Of hoOauth To "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
    Set ComTokenEndpoint Of hoOauth To "https://login.microsoftonline.com/common/oauth2/v2.0/token"
    Set ComClientId Of hoOauth To "YOUR_APPLICATION_CLIENT_ID"
    //  Public desktop applications cannot keep a client secret. Use PKCE instead.
    Set ComLocalHost Of hoOauth To "localhost"
    Set ComListenPort Of hoOauth To 3017
    Set ComCodeChallenge Of hoOauth To True
    Set ComCodeChallengeMethod Of hoOauth To "S256"
    //  ReadWrite covers this collection's create/delete operations. Use ReadBasic for basic lists only.
    Set ComScope Of hoOauth To "offline_access https://graph.microsoft.com/Calendars.ReadWrite"
    Get ComAddAuthQueryParam Of hoOauth "prompt" "select_account" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not configure the authorization request."
        Procedure_Return
    End

    Get ComStartAuth Of hoOauth To sAuthUrl
    Get ComLastMethodSuccess Of hoOauth To bTemp1
    If (bTemp1 <> True) Begin
        Showln "Could not start the local authorization 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
    Set ComStrict Of hoToken To True
    Get ComAccessTokenResponse Of hoOauth To sTemp1
    Get ComLoad Of hoToken sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not parse the token response; existing cache unchanged."
        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 "Expected a nonempty access_token in the JSON."
        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 "Expected a nonempty refresh_token in the JSON."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoToken "expires_in" To iTemp1
    Get ComIntOf Of hoToken "expires_in" To iTemp2
    If ((iTemp1 <> 2) Or (iTemp2 <= 0)) Begin
        Showln "Expected a positive access-token lifetime."
        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
    If (iSuccess <> True) Begin
        Showln "Could not record the token acquisition time."
        Procedure_Return
    End

    Get ComGetAsTimestamp Of hoObtained False To sTemp1
    Get ComUpdateString Of hoToken "obtained_at" sTemp1 To iSuccess
    //  This file contains credentials. Choose an access-controlled directory for the signed-in account.
    Get Create (RefClass(cComCkFileAccess)) To hoFac
    If (Not(IsComObjectCreated(hoFac))) Begin
        Send CreateComObject of hoFac
    End
    Get ComDirEnsureExists Of hoFac "qa_data/tokens" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not create the private token-cache directory."
        Procedure_Return
    End

    Get ComWriteFile Of hoToken "qa_data/tokens/outlookCalendar.json" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not save the token cache."
        Procedure_Return
    End

    //  Never print access_token, refresh_token, or the complete token response.
    Showln "Calendar authorization completed; token cache saved."


End_Procedure