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

OneDrive: Refresh a Delegated Access Token

See more OneDrive Examples

Refresh the token from OneDrive authorization with PKCE, using the same application client ID and authority. This retains the user grant; it does not convert it to application access. Omitting scope retains the existing scopes. Obtain additional consent through authorization when needed.

The private oneDrive.json token cache is replaced only after a successful, validated response. Retain the previous refresh token when no replacement is returned, and save a rotated refresh token when supplied. A private backup is written first; production storage should use atomic replacement and a single refresh writer per account/application. invalid_grant or an interaction requirement requires sign-in again. Tokens and raw responses are not printed.

Permission: The original delegated grant.

Check the expected HTTP status before using a response body. A false method result can still contain an HTTP error response; status zero means no response arrived. For 401, renew authorization; for 403, check permissions, access grants, and policy; for 429, honor Retry-After with a bounded retry. Reconcile uncertain writes before repeating them. Keep credentials, file contents, upload/download URLs, and detailed diagnostics 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/oneDrive.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/oneDrive.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/oneDrive.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 OneDrive token cache."


End_Procedure