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

Outlook Contacts: Refresh a Delegated Access Token

See more Outlook Contact Examples

After interactive authorization, refresh the Graph access token without reopening a browser. Use the same app client ID and authority as the contacts OAuth2 example. Omitting scope retains the original grant. This is delegated access, not application authentication; invalid_grant or an interaction requirement needs fresh interactive authorization.

The example validates the response, retains the previous refresh token when no replacement is returned, and saves a rotated token when present. HTTP or validation failures leave the old cache unchanged. A private backup protects against replacement-write failure; production applications should use protected atomic credential storage and serialize refreshes per account. Tokens are never printed.

Uses qa_data/tokens/outlookContacts.json. Refresh before the acquired time plus expires_in lifetime elapses. Keep the cache associated with its original app and account.

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 contact data private.

Microsoft documentation

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoToken
    String sClientId
    String sTokenUrl
    Handle hoHttp
    Variant vReq
    Handle hoReq
    Variant vResp
    Handle hoResp
    Handle hoResult
    Handle hoObtained
    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(cComChilkatJsonObject)) To hoToken
    If (Not(IsComObjectCreated(hoToken))) Begin
        Send CreateComObject of hoToken
    End
    Set ComStrict Of hoToken To True
    Get ComLoadFile Of hoToken "qa_data/tokens/outlookContacts.json" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Read the private token cache or authorize again."
        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

    Move "YOUR_APPLICATION_CLIENT_ID" To sClientId
    //  Use the same app and authority as the original authorization.
    Move "https://login.microsoftonline.com/common/oauth2/v2.0/token" To sTokenUrl
    Get Create (RefClass(cComChilkatHttp)) To hoHttp
    If (Not(IsComObjectCreated(hoHttp))) Begin
        Send CreateComObject of hoHttp
    End
    Set ComRequireSslCertVerify Of hoHttp To True
    Set ComFollowRedirects Of hoHttp To False
    Set ComConnectTimeout Of hoHttp To 20
    Set ComReadTimeout Of hoHttp To 30
    Get Create (RefClass(cComChilkatHttpRequest)) To hoReq
    If (Not(IsComObjectCreated(hoReq))) Begin
        Send CreateComObject of hoReq
    End
    Set ComHttpVerb Of hoReq To "POST"
    Set ComContentType Of hoReq To "application/x-www-form-urlencoded"
    Send ComAddParam To hoReq "client_id" sClientId
    Send ComAddParam To hoReq "grant_type" "refresh_token"
    Get ComStringOf Of hoToken "refresh_token" To sTemp1
    Send ComAddParam To hoReq "refresh_token" sTemp1
    //  Omitting scope retains the original grant instead of requesting additional permissions.
    Get Create (RefClass(cComChilkatHttpResponse)) To hoResp
    If (Not(IsComObjectCreated(hoResp))) Begin
        Send CreateComObject of hoResp
    End
    Get Create (RefClass(cComChilkatJsonObject)) To hoResult
    If (Not(IsComObjectCreated(hoResult))) Begin
        Send CreateComObject of hoResult
    End
    Set ComStrict Of hoResult To True
    Get pvComObject of hoReq to vReq
    Get pvComObject of hoResp to vResp
    Get ComHttpReq Of hoHttp sTokenUrl vReq vResp To iSuccess
    //  A false result can still include an HTTP error response.
    Get ComStatusCode Of hoResp To iTemp1
    If ((iSuccess <> True) And (iTemp1 = 0)) Begin
        Showln "No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying."
        Procedure_Return
    End

    Get ComStatusCode Of hoResp To iTemp1
    If (iTemp1 <> 200) Begin
        Get ComStatusCode Of hoResp To iTemp1
        Showln "Unexpected HTTP status: " iTemp1
        Get ComGetHeaderField Of hoResp "request-id" To sTemp1
        Showln "Request ID: " sTemp1
        Get ComStatusCode Of hoResp To iTemp1
        If (iTemp1 = 429) Begin
            Get ComGetHeaderField Of hoResp "Retry-After" To sTemp1
            Showln "Retry-After: " sTemp1
        End

        Get ComStatusCode Of hoResp To iTemp1
        If (iTemp1 = 401) Begin
            Showln "Refresh the Graph access token or authorize again."
        End

        Procedure_Return
    End

    Get ComBodyStr Of hoResp To sTemp1
    Get ComLoad Of hoResult sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Expected a well-formed JSON response."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoResult "access_token" To iTemp1
    Get ComStringOfEquals Of hoResult "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 hoResult "expires_in" To iTemp1
    Get ComIntOf Of hoResult "expires_in" To iTemp2
    If ((iTemp1 <> 2) Or (iTemp2 <= 0)) Begin
        Showln "Missing token lifetime; old cache unchanged."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoResult "refresh_token" To iTemp1
    If (iTemp1 = -1) Begin
        Get ComStringOf Of hoToken "refresh_token" To sTemp1
        Get ComUpdateString Of hoResult "refresh_token" sTemp1 To iSuccess
    End
    Else Begin
        Get ComJsonTypeOf Of hoResult "refresh_token" To iTemp1
        Get ComStringOfEquals Of hoResult "refresh_token" "" True To bTemp1
        If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
            Showln "Expected a nonempty refresh_token in the JSON."
            Procedure_Return
        End

    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 timestamp the refreshed token."
        Procedure_Return
    End

    Get ComGetAsTimestamp Of hoObtained False To sTemp1
    Get ComUpdateString Of hoResult "obtained_at" sTemp1 To iSuccess
    //  Keep a valid previous cache for recovery if the replacement write fails.
    Get ComWriteFile Of hoToken "qa_data/tokens/outlookContacts.json.bak" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not back up the old cache; no replacement attempted."
        Procedure_Return
    End

    Get ComWriteFile Of hoResult "qa_data/tokens/outlookContacts.json" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not save the new token; recover the previous cache from the private .bak file."
        Procedure_Return
    End

    Showln "Refreshed the contacts token cache."


End_Procedure