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

OneDrive: Obtain and Refresh a SharePoint Transfer Token

See more OneDrive Examples

Obtain and refresh a delegated SharePoint Online access token for the OneDrive download, upload-session, version-download, and copy-monitor examples. This is for Microsoft 365 work/school accounts, not personal OneDrive. It saves qa_data/tokens/oneDrive-sharepoint.json with the exact host and access_token those transfer examples read, plus a refresh token, lifetime, acquisition time, and cache context. The Graph cache oneDrive.json remains separate.

Register a public application in Microsoft Entra, select the intended organizational account type, and add http://localhost:3017/ as a Mobile and desktop applications redirect URI. Set tenantId to the Directory (tenant) GUID and clientId to the Application (client) ID. Add the appropriate SharePoint delegated permissions in API permissions: use MyFiles.Read for reading the user's files or MyFiles.Write for writing them; use AllSites.Read or AllSites.Write where broader SharePoint site access is needed. Select only the permissions required and obtain consent as tenant policy requires. The user's actual access still applies. Graph permissions alone do not establish this SharePoint grant.

Set sharepointHost from trusted configuration: typically tenant.sharepoint.com for SharePoint libraries or tenant-my.sharepoint.com for the user's business OneDrive. Use the exact host expected by the transfer examples, without a scheme, path, port, or wildcard. This global-cloud example requests https://{host}/.default, which uses configured, consented SharePoint permissions, plus offline_access during authorization. Do not combine .default with dynamic API permission scopes. If newly configured permissions are not already consented, arrange renewed consent; refreshing does not grant them. How .default consent works.

Run action="authorize" for initial PKCE browser sign-in, choosing the same intended user as the Graph workflow. This explicitly replaces an existing cache after validation and backup. Change to action="refresh" for unattended renewal before obtained_at plus expires_in, allowing a safety margin. Refresh sends an explicit SharePoint resource scope and never opens a browser automatically. It saves a rotated refresh token, or retains the previous one when omitted. Revocation, Conditional Access, invalid_grant, or interaction requirements can require a new sign-in.

The local accountKey is an application-defined cache key, not a verified identity claim. The refresh branch requires matching host, tenant, client, account key, and resource scope before sending credentials. Use separate protected caches for different contexts and update the transfer cache path accordingly. Existing hand-written caches without the refresh/context fields need authorize. Do not decode an access token and assume its internal format or audience claim is a stable client contract.

Only validated responses replace the cache. A checked private backup supports recovery; production applications should serialize refreshes and commit credentials atomically in protected storage. Neither token is printed. A loopback listener is required only for initial sign-in; no hosted web server is needed. This is not certificate-based application access, which obtains new tokens through client credentials and has no refresh token.

OneDrive transfer authentication guide. Microsoft's SharePoint delegated permission overview.

Permission: Configured SharePoint delegated permissions and offline_access.

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
    String sAction
    String sTenantId
    String sClientId
    String sSharepointHost
    String sAccountKey
    String sCachePath
    String sBackupPath
    Handle hoHost
    Variant vMatch
    Handle hoMatch
    Integer iMatched
    Handle hoTenant
    Handle hoHttp
    Handle hoTokenEndpoint
    Handle hoAuthorizeEndpoint
    Handle hoScopeBuilder
    String sResourceScope
    Handle hoFac
    Boolean iHadCache
    Handle hoPrevious
    Handle hoResult
    Handle hoOauth
    Handle hoScopes
    String sAuthUrl
    Integer iWaited
    Variant vReq
    Handle hoReq
    Variant vResp
    Handle hoResp
    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
    //  Run authorize once; change to refresh for subsequent unattended renewals.
    Move "authorize" To sAction
    Move "YOUR_TENANT_ID" To sTenantId
    Move "YOUR_APPLICATION_CLIENT_ID" To sClientId
    //  A trusted bare hostname, e.g. tenant.sharepoint.com or tenant-my.sharepoint.com.
    //  Configure the exact host used by the intended transfer; do not copy an untrusted URL here.
    Move "YOUR_TENANT.sharepoint.com" To sSharepointHost
    //  An application-defined key for this user/account, not an access token or password.
    Move "YOUR_LOCAL_ACCOUNT_KEY" To sAccountKey
    Move "qa_data/tokens/oneDrive-sharepoint.json" To sCachePath
    Move "qa_data/tokens/oneDrive-sharepoint.json.bak" To sBackupPath
    If ((sAction <> "authorize") And (sAction <> "refresh")) Begin
        Showln "Choose authorize or refresh."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatStringBuilder)) To hoHost
    If (Not(IsComObjectCreated(hoHost))) Begin
        Send CreateComObject of hoHost
    End
    Get ComAppend Of hoHost sSharepointHost To iSuccess
    Get Create (RefClass(cComChilkatJsonObject)) To hoMatch
    If (Not(IsComObjectCreated(hoMatch))) Begin
        Send CreateComObject of hoMatch
    End
    Get pvComObject of hoMatch to vMatch
    Get ComRegexMatch Of hoHost "(?i)\A[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.sharepoint\.com\z" vMatch 100 To iMatched
    If (iMatched <> 1) Begin
        Showln "Set the trusted SharePoint hostname for this global-cloud example, without a scheme, path, or port."
        Procedure_Return
    End

    //  Use the organization's Directory (tenant) ID, not common, organizations, or consumers.
    Get Create (RefClass(cComChilkatStringBuilder)) To hoTenant
    If (Not(IsComObjectCreated(hoTenant))) Begin
        Send CreateComObject of hoTenant
    End
    Get ComAppend Of hoTenant sTenantId To iSuccess
    Get pvComObject of hoMatch to vMatch
    Get ComRegexMatch Of hoTenant "(?i)\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z" vMatch 100 To iMatched
    If (iMatched <> 1) Begin
        Showln "Set the organization tenant GUID before running."
        Procedure_Return
    End

    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(cComChilkatStringBuilder)) To hoTokenEndpoint
    If (Not(IsComObjectCreated(hoTokenEndpoint))) Begin
        Send CreateComObject of hoTokenEndpoint
    End
    Get ComAppend Of hoTokenEndpoint "https://login.microsoftonline.com/" To iSuccess
    Get ComUrlEncode Of hoHttp sTenantId To sTemp1
    Get ComAppend Of hoTokenEndpoint sTemp1 To iSuccess
    Get ComAppend Of hoTokenEndpoint "/oauth2/v2.0/token" To iSuccess
    Get Create (RefClass(cComChilkatStringBuilder)) To hoAuthorizeEndpoint
    If (Not(IsComObjectCreated(hoAuthorizeEndpoint))) Begin
        Send CreateComObject of hoAuthorizeEndpoint
    End
    Get ComAppend Of hoAuthorizeEndpoint "https://login.microsoftonline.com/" To iSuccess
    Get ComUrlEncode Of hoHttp sTenantId To sTemp1
    Get ComAppend Of hoAuthorizeEndpoint sTemp1 To iSuccess
    Get ComAppend Of hoAuthorizeEndpoint "/oauth2/v2.0/authorize" To iSuccess
    Get Create (RefClass(cComChilkatStringBuilder)) To hoScopeBuilder
    If (Not(IsComObjectCreated(hoScopeBuilder))) Begin
        Send CreateComObject of hoScopeBuilder
    End
    Get ComAppend Of hoScopeBuilder "https://" To iSuccess
    Get ComAppend Of hoScopeBuilder sSharepointHost To iSuccess
    Get ComAppend Of hoScopeBuilder "/.default" To iSuccess
    Get ComGetAsString Of hoScopeBuilder To sResourceScope
    Get Create (RefClass(cComCkFileAccess)) To hoFac
    If (Not(IsComObjectCreated(hoFac))) Begin
        Send CreateComObject of hoFac
    End
    Get ComFileExists Of hoFac sCachePath To iHadCache
    Get Create (RefClass(cComChilkatJsonObject)) To hoPrevious
    If (Not(IsComObjectCreated(hoPrevious))) Begin
        Send CreateComObject of hoPrevious
    End
    Set ComStrict Of hoPrevious To True
    If (iHadCache = True) Begin
        Get ComLoadFile Of hoPrevious sCachePath To iSuccess
        If (iSuccess <> True) Begin
            Showln "Invalid existing cache; recover its private backup before continuing."
            Procedure_Return
        End

    End

    Get Create (RefClass(cComChilkatJsonObject)) To hoResult
    If (Not(IsComObjectCreated(hoResult))) Begin
        Send CreateComObject of hoResult
    End
    Set ComStrict Of hoResult To True
    If (sAction = "authorize") Begin
        //  Register http://localhost:3017/ as a Mobile and desktop applications redirect URI.
        Get Create (RefClass(cComChilkatOAuth2)) To hoOauth
        If (Not(IsComObjectCreated(hoOauth))) Begin
            Send CreateComObject of hoOauth
        End
        Get ComGetAsString Of hoAuthorizeEndpoint To sTemp1
        Set ComAuthorizationEndpoint Of hoOauth To sTemp1
        Get ComGetAsString Of hoTokenEndpoint To sTemp1
        Set ComTokenEndpoint Of hoOauth To sTemp1
        Set ComClientId Of hoOauth To sClientId
        Set ComLocalHost Of hoOauth To "localhost"
        Set ComListenPort Of hoOauth To 3017
        Set ComCodeChallenge Of hoOauth To True
        Set ComCodeChallengeMethod Of hoOauth To "S256"
        //  No client secret in a public desktop application.
        Get Create (RefClass(cComChilkatStringBuilder)) To hoScopes
        If (Not(IsComObjectCreated(hoScopes))) Begin
            Send CreateComObject of hoScopes
        End
        Get ComAppend Of hoScopes "offline_access " To iSuccess
        Get ComAppend Of hoScopes sResourceScope To iSuccess
        Get ComGetAsString Of hoScopes To sTemp1
        Set ComScope Of hoOauth To sTemp1
        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 ComAccessTokenResponse Of hoOauth To sTemp1
        Get ComLoad Of hoResult sTemp1 To iSuccess
        If (iSuccess <> True) Begin
            Showln "Invalid token response; existing cache unchanged."
            Procedure_Return
        End

        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
    Else Begin
        If (iHadCache <> True) Begin
            Showln "No SharePoint token cache. Run authorize first."
            Procedure_Return
        End

        Get ComStringOfEquals Of hoPrevious "host" sSharepointHost True To bTemp1
        If (bTemp1 <> True) Begin
            Showln "Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache."
            Procedure_Return
        End

        Get ComStringOfEquals Of hoPrevious "tenant_id" sTenantId True To bTemp1
        If (bTemp1 <> True) Begin
            Showln "Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache."
            Procedure_Return
        End

        Get ComStringOfEquals Of hoPrevious "client_id" sClientId True To bTemp1
        If (bTemp1 <> True) Begin
            Showln "Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache."
            Procedure_Return
        End

        Get ComStringOfEquals Of hoPrevious "account_key" sAccountKey True To bTemp1
        If (bTemp1 <> True) Begin
            Showln "Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache."
            Procedure_Return
        End

        Get ComStringOfEquals Of hoPrevious "resource_scope" sResourceScope True To bTemp1
        If (bTemp1 <> True) Begin
            Showln "Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache."
            Procedure_Return
        End

        Get ComJsonTypeOf Of hoPrevious "refresh_token" To iTemp1
        Get ComStringOfEquals Of hoPrevious "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 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 hoPrevious "refresh_token" To sTemp1
        Send ComAddParam To hoReq "refresh_token" sTemp1
        //  Explicit resource scope keeps the renewal on SharePoint, not Microsoft Graph.
        Send ComAddParam To hoReq "scope" sResourceScope
        Get Create (RefClass(cComChilkatHttpResponse)) To hoResp
        If (Not(IsComObjectCreated(hoResp))) Begin
            Send CreateComObject of hoResp
        End
        Get ComGetAsString Of hoTokenEndpoint To sTemp1
        Get pvComObject of hoReq to vReq
        Get pvComObject of hoResp to vResp
        Get ComHttpReq Of hoHttp sTemp1 vReq vResp To iSuccess
        Get ComStatusCode Of hoResp To iTemp1
        If ((iSuccess <> True) And (iTemp1 = 0)) Begin
            Showln "No token response received; existing cache unchanged."
            Procedure_Return
        End

        Get ComStatusCode Of hoResp To iTemp1
        If (iTemp1 <> 200) Begin
            Get ComStatusCode Of hoResp To iTemp1
            Showln "Token renewal failed. HTTP status: " iTemp1
            Get ComStatusCode Of hoResp To iTemp1
            If (iTemp1 = 429) Begin
                Get ComGetHeaderField Of hoResp "Retry-After" To sTemp1
                Showln "Retry-After: " sTemp1
            End

            Showln "Check consent and token validity. If interaction is required, run authorize deliberately."
            Procedure_Return
        End

        If (iSuccess <> True) Begin
            Showln "Token response did not complete; existing cache unchanged."
            Procedure_Return
        End

        Get ComBodyStr Of hoResp To sTemp1
        Get ComLoad Of hoResult sTemp1 To iSuccess
        If (iSuccess <> True) Begin
            Showln "Invalid refresh response; existing cache unchanged."
            Procedure_Return
        End

        Get ComJsonTypeOf Of hoResult "refresh_token" To iTemp1
        If (iTemp1 = -1) Begin
            Get ComStringOf Of hoPrevious "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

    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 "Expected a positive access-token lifetime; existing cache unchanged."
        Procedure_Return
    End

    Get ComStringOfEquals Of hoResult "token_type" "Bearer" False To bTemp1
    If (bTemp1 <> True) Begin
        Showln "Expected a bearer access token; existing cache unchanged."
        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 timestamp the access token."
        Procedure_Return
    End

    Get ComGetAsTimestamp Of hoObtained False To sTemp1
    Get ComUpdateString Of hoResult "obtained_at" sTemp1 To iSuccess
    //  The transfer examples read host and access_token; these extra fields bind future refreshes.
    Get ComUpdateString Of hoResult "host" sSharepointHost To iSuccess
    Get ComUpdateString Of hoResult "tenant_id" sTenantId To iSuccess
    Get ComUpdateString Of hoResult "client_id" sClientId To iSuccess
    Get ComUpdateString Of hoResult "account_key" sAccountKey To iSuccess
    Get ComUpdateString Of hoResult "resource_scope" sResourceScope To iSuccess
    Get ComDirEnsureExists Of hoFac "qa_data/tokens" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not create the private cache directory."
        Procedure_Return
    End

    If (iHadCache = True) Begin
        Get ComWriteFile Of hoPrevious sBackupPath To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not back up the previous cache; no replacement attempted."
            Procedure_Return
        End

    End

    Get ComWriteFile Of hoResult sCachePath To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not save the new cache; recover the private backup if an older cache existed."
        Procedure_Return
    End

    //  Never print the tokens, token response, or authorization URL.
    Showln "SharePoint token cache saved. The OneDrive transfer examples can now load it."


End_Procedure