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

B4X
Dim success As Boolean = False

'  Assumes Chilkat is unlocked. See Global Unlock Sample.
success = False
'  Run authorize once; change to refresh for subsequent unattended renewals.
Dim action As String = "authorize"
Dim tenantId As String = "YOUR_TENANT_ID"
Dim clientId As String = "YOUR_APPLICATION_CLIENT_ID"
'  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.
Dim sharepointHost As String = "YOUR_TENANT.sharepoint.com"
'  An application-defined key for this user/account, not an access token or password.
Dim accountKey As String = "YOUR_LOCAL_ACCOUNT_KEY"
Dim cachePath As String = "qa_data/tokens/oneDrive-sharepoint.json"
Dim backupPath As String = "qa_data/tokens/oneDrive-sharepoint.json.bak"
If (action <> "authorize") And (action <> "refresh") Then
    Log("Choose authorize or refresh.")
    Return
End If

Dim host As ChilkatStringBuilder
host.Initialize
host.Append(sharepointHost)
Dim match As ChilkatJsonObject
match.Initialize
Dim matched As Int = host.RegexMatch("(?i)\A[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.sharepoint\.com\z", match, 100)
If matched <> 1 Then
    Log("Set the trusted SharePoint hostname for this global-cloud example, without a scheme, path, or port.")
    Return
End If

'  Use the organization's Directory (tenant) ID, not common, organizations, or consumers.
Dim tenant As ChilkatStringBuilder
tenant.Initialize
tenant.Append(tenantId)
matched = tenant.RegexMatch("(?i)\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z", match, 100)
If matched <> 1 Then
    Log("Set the organization tenant GUID before running.")
    Return
End If

Dim http As ChilkatHttp
http.Initialize("http")
http.RequireSslCertVerify = True
http.FollowRedirects = False
http.ConnectTimeout = 20
http.ReadTimeout = 30
Dim tokenEndpoint As ChilkatStringBuilder
tokenEndpoint.Initialize
tokenEndpoint.Append("https://login.microsoftonline.com/")
tokenEndpoint.Append(http.UrlEncode(tenantId))
tokenEndpoint.Append("/oauth2/v2.0/token")
Dim authorizeEndpoint As ChilkatStringBuilder
authorizeEndpoint.Initialize
authorizeEndpoint.Append("https://login.microsoftonline.com/")
authorizeEndpoint.Append(http.UrlEncode(tenantId))
authorizeEndpoint.Append("/oauth2/v2.0/authorize")
Dim scopeBuilder As ChilkatStringBuilder
scopeBuilder.Initialize
scopeBuilder.Append("https://")
scopeBuilder.Append(sharepointHost)
scopeBuilder.Append("/.default")
Dim resourceScope As String = scopeBuilder.GetAsString
Dim fac As ChilkatFileAccess
fac.Initialize
Dim hadCache As Boolean = fac.FileExists(cachePath)
Dim previous As ChilkatJsonObject
previous.Initialize
previous.Strict = True
If hadCache = True Then
    success = previous.LoadFile(cachePath)
    If success <> True Then
        Log("Invalid existing cache; recover its private backup before continuing.")
        Return
    End If

End If

Dim result As ChilkatJsonObject
result.Initialize
result.Strict = True
If action = "authorize" Then
    '  Register http://localhost:3017/ as a Mobile and desktop applications redirect URI.
    Dim oauth As ChilkatOAuth2
    oauth.Initialize("oauth")
    oauth.AuthorizationEndpoint = authorizeEndpoint.GetAsString
    oauth.TokenEndpoint = tokenEndpoint.GetAsString
    oauth.ClientId = clientId
    oauth.LocalHost = "localhost"
    oauth.ListenPort = 3017
    oauth.CodeChallenge = True
    oauth.CodeChallengeMethod = "S256"
    '  No client secret in a public desktop application.
    Dim scopes As ChilkatStringBuilder
    scopes.Initialize
    scopes.Append("offline_access ")
    scopes.Append(resourceScope)
    oauth.Scope = scopes.GetAsString
    success = oauth.AddAuthQueryParam("prompt", "select_account")
    If success <> True Then
        Log("Could not configure the authorization request.")
        Return
    End If

    Dim authUrl As String = oauth.StartAuth
    If oauth.LastMethodSuccess <> True Then
        Log("Could not start the local authorization listener.")
        Return
    End If

    success = oauth.LaunchBrowser(authUrl)
    If success <> True Then
        oauth.Cancel
        Log("Could not open the system browser.")
        Return
    End If

    Dim waited As Int = 0
    Do While ((oauth.AuthFlowState < 3) And (waited < 180000))
        oauth.SleepMs(200)
        waited = waited + 200
    Loop
    If oauth.AuthFlowState < 3 Then
        oauth.Cancel
        Log("Authorization timed out.")
        Return
    End If

    If oauth.AuthFlowState <> 3 Then
        Log("Authorization did not complete. Flow state: " & oauth.AuthFlowState)
        Return
    End If

    success = result.Load(oauth.AccessTokenResponse)
    If success <> True Then
        Log("Invalid token response; existing cache unchanged.")
        Return
    End If

    If (result.JsonTypeOf("refresh_token") <> 1) Or (result.StringOfEquals("refresh_token", "", True) = True) Then
        Log("Expected a nonempty refresh_token in the JSON.")
        Return
    End If

Else
    If hadCache <> True Then
        Log("No SharePoint token cache. Run authorize first.")
        Return
    End If

    If previous.StringOfEquals("host", sharepointHost, True) <> True Then
        Log("Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.")
        Return
    End If

    If previous.StringOfEquals("tenant_id", tenantId, True) <> True Then
        Log("Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.")
        Return
    End If

    If previous.StringOfEquals("client_id", clientId, True) <> True Then
        Log("Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.")
        Return
    End If

    If previous.StringOfEquals("account_key", accountKey, True) <> True Then
        Log("Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.")
        Return
    End If

    If previous.StringOfEquals("resource_scope", resourceScope, True) <> True Then
        Log("Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.")
        Return
    End If

    If (previous.JsonTypeOf("refresh_token") <> 1) Or (previous.StringOfEquals("refresh_token", "", True) = True) Then
        Log("Expected a nonempty refresh_token in the JSON.")
        Return
    End If

    Dim req As ChilkatHttpRequest
    req.Initialize
    req.HttpVerb = "POST"
    req.ContentType = "application/x-www-form-urlencoded"
    req.AddParam("client_id", clientId)
    req.AddParam("grant_type", "refresh_token")
    req.AddParam("refresh_token", previous.StringOf("refresh_token"))
    '  Explicit resource scope keeps the renewal on SharePoint, not Microsoft Graph.
    req.AddParam("scope", resourceScope)
    Dim resp As ChilkatHttpResponse
    resp.Initialize
    success = http.HttpReq(tokenEndpoint.GetAsString, req, resp)
    If (success <> True) And (resp.StatusCode = 0) Then
        Log("No token response received; existing cache unchanged.")
        Return
    End If

    If resp.StatusCode <> 200 Then
        Log("Token renewal failed. HTTP status: " & resp.StatusCode)
        If resp.StatusCode = 429 Then
            Log("Retry-After: " & resp.GetHeaderField("Retry-After"))
        End If

        Log("Check consent and token validity. If interaction is required, run authorize deliberately.")
        Return
    End If

    If success <> True Then
        Log("Token response did not complete; existing cache unchanged.")
        Return
    End If

    success = result.Load(resp.BodyStr)
    If success <> True Then
        Log("Invalid refresh response; existing cache unchanged.")
        Return
    End If

    If result.JsonTypeOf("refresh_token") = -1 Then
        result.UpdateString("refresh_token", previous.StringOf("refresh_token"))
    Else
        If (result.JsonTypeOf("refresh_token") <> 1) Or (result.StringOfEquals("refresh_token", "", True) = True) Then
            Log("Expected a nonempty refresh_token in the JSON.")
            Return
        End If

    End If

End If

If (result.JsonTypeOf("access_token") <> 1) Or (result.StringOfEquals("access_token", "", True) = True) Then
    Log("Expected a nonempty access_token in the JSON.")
    Return
End If

If (result.JsonTypeOf("expires_in") <> 2) Or (result.IntOf("expires_in") <= 0) Then
    Log("Expected a positive access-token lifetime; existing cache unchanged.")
    Return
End If

If result.StringOfEquals("token_type", "Bearer", False) <> True Then
    Log("Expected a bearer access token; existing cache unchanged.")
    Return
End If

Dim obtained As ChilkatDateTime
obtained.Initialize
success = obtained.SetFromCurrentSystemTime
If success <> True Then
    Log("Could not timestamp the access token.")
    Return
End If

result.UpdateString("obtained_at", obtained.GetAsTimestamp(False))
'  The transfer examples read host and access_token; these extra fields bind future refreshes.
result.UpdateString("host", sharepointHost)
result.UpdateString("tenant_id", tenantId)
result.UpdateString("client_id", clientId)
result.UpdateString("account_key", accountKey)
result.UpdateString("resource_scope", resourceScope)
success = fac.DirEnsureExists("qa_data/tokens")
If success <> True Then
    Log("Could not create the private cache directory.")
    Return
End If

If hadCache = True Then
    success = previous.WriteFile(backupPath)
    If success <> True Then
        Log("Could not back up the previous cache; no replacement attempted.")
        Return
    End If

End If

success = result.WriteFile(cachePath)
If success <> True Then
    Log("Could not save the new cache; recover the private backup if an older cache existed.")
    Return
End If

'  Never print the tokens, token response, or authorization URL.
Log("SharePoint token cache saved. The OneDrive transfer examples can now load it.")