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.
Chilkat Xojo Plugin Downloads
Dim success As Boolean
success = 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
action = "authorize"
Dim tenantId As String
tenantId = "YOUR_TENANT_ID"
Dim clientId As String
clientId = "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
sharepointHost = "YOUR_TENANT.sharepoint.com"
// An application-defined key for this user/account, not an access token or password.
Dim accountKey As String
accountKey = "YOUR_LOCAL_ACCOUNT_KEY"
Dim cachePath As String
cachePath = "qa_data/tokens/oneDrive-sharepoint.json"
Dim backupPath As String
backupPath = "qa_data/tokens/oneDrive-sharepoint.json.bak"
If ((action <> "authorize") And (action <> "refresh")) Then
System.DebugLog("Choose authorize or refresh.")
Return
End If
Dim host As New Chilkat.StringBuilder
success = host.Append(sharepointHost)
Dim match As New Chilkat.JsonObject
Dim matched As Int32
matched = host.RegexMatch("(?i)\A[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.sharepoint\.com\z",match,100)
If (matched <> 1) Then
System.DebugLog("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 New Chilkat.StringBuilder
success = 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
System.DebugLog("Set the organization tenant GUID before running.")
Return
End If
Dim http As New Chilkat.Http
http.RequireSslCertVerify = True
http.FollowRedirects = False
http.ConnectTimeout = 20
http.ReadTimeout = 30
Dim tokenEndpoint As New Chilkat.StringBuilder
success = tokenEndpoint.Append("https://login.microsoftonline.com/")
success = tokenEndpoint.Append(http.UrlEncode(tenantId))
success = tokenEndpoint.Append("/oauth2/v2.0/token")
Dim authorizeEndpoint As New Chilkat.StringBuilder
success = authorizeEndpoint.Append("https://login.microsoftonline.com/")
success = authorizeEndpoint.Append(http.UrlEncode(tenantId))
success = authorizeEndpoint.Append("/oauth2/v2.0/authorize")
Dim scopeBuilder As New Chilkat.StringBuilder
success = scopeBuilder.Append("https://")
success = scopeBuilder.Append(sharepointHost)
success = scopeBuilder.Append("/.default")
Dim resourceScope As String
resourceScope = scopeBuilder.GetAsString()
Dim fac As New Chilkat.FileAccess
Dim hadCache As Boolean
hadCache = fac.FileExists(cachePath)
Dim previous As New Chilkat.JsonObject
previous.Strict = True
If (hadCache = True) Then
success = previous.LoadFile(cachePath)
If (success <> True) Then
System.DebugLog("Invalid existing cache; recover its private backup before continuing.")
Return
End If
End If
Dim result As New Chilkat.JsonObject
result.Strict = True
If (action = "authorize") Then
// Register http://localhost:3017/ as a Mobile and desktop applications redirect URI.
Dim oauth As New Chilkat.OAuth2
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 New Chilkat.StringBuilder
success = scopes.Append("offline_access ")
success = scopes.Append(resourceScope)
oauth.Scope = scopes.GetAsString()
success = oauth.AddAuthQueryParam("prompt","select_account")
If (success <> True) Then
System.DebugLog("Could not configure the authorization request.")
Return
End If
Dim authUrl As String
authUrl = oauth.StartAuth()
If (oauth.LastMethodSuccess <> True) Then
System.DebugLog("Could not start the local authorization listener.")
Return
End If
success = oauth.LaunchBrowser(authUrl)
If (success <> True) Then
success = oauth.Cancel()
System.DebugLog("Could not open the system browser.")
Return
End If
Dim waited As Int32
waited = 0
While ((oauth.AuthFlowState < 3) And (waited < 180000))
oauth.SleepMs 200
waited = waited + 200
Wend
If (oauth.AuthFlowState < 3) Then
success = oauth.Cancel()
System.DebugLog("Authorization timed out.")
Return
End If
If (oauth.AuthFlowState <> 3) Then
System.DebugLog("Authorization did not complete. Flow state: " + Str(oauth.AuthFlowState))
Return
End If
success = result.Load(oauth.AccessTokenResponse)
If (success <> True) Then
System.DebugLog("Invalid token response; existing cache unchanged.")
Return
End If
If ((result.JsonTypeOf("refresh_token") <> 1) Or (result.StringOfEquals("refresh_token","",True) = True)) Then
System.DebugLog("Expected a nonempty refresh_token in the JSON.")
Return
End If
Else
If (hadCache <> True) Then
System.DebugLog("No SharePoint token cache. Run authorize first.")
Return
End If
If (previous.StringOfEquals("host",sharepointHost,True) <> True) Then
System.DebugLog("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
System.DebugLog("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
System.DebugLog("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
System.DebugLog("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
System.DebugLog("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
System.DebugLog("Expected a nonempty refresh_token in the JSON.")
Return
End If
Dim req As New Chilkat.HttpRequest
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 New Chilkat.HttpResponse
success = http.HttpReq(tokenEndpoint.GetAsString(),req,resp)
If ((success <> True) And (resp.StatusCode = 0)) Then
System.DebugLog("No token response received; existing cache unchanged.")
Return
End If
If (resp.StatusCode <> 200) Then
System.DebugLog("Token renewal failed. HTTP status: " + Str(resp.StatusCode))
If (resp.StatusCode = 429) Then
System.DebugLog("Retry-After: " + resp.GetHeaderField("Retry-After"))
End If
System.DebugLog("Check consent and token validity. If interaction is required, run authorize deliberately.")
Return
End If
If (success <> True) Then
System.DebugLog("Token response did not complete; existing cache unchanged.")
Return
End If
success = result.Load(resp.BodyStr)
If (success <> True) Then
System.DebugLog("Invalid refresh response; existing cache unchanged.")
Return
End If
If (result.JsonTypeOf("refresh_token") = -1) Then
success = result.UpdateString("refresh_token",previous.StringOf("refresh_token"))
Else
If ((result.JsonTypeOf("refresh_token") <> 1) Or (result.StringOfEquals("refresh_token","",True) = True)) Then
System.DebugLog("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
System.DebugLog("Expected a nonempty access_token in the JSON.")
Return
End If
If ((result.JsonTypeOf("expires_in") <> 2) Or (result.IntOf("expires_in") <= 0)) Then
System.DebugLog("Expected a positive access-token lifetime; existing cache unchanged.")
Return
End If
If (result.StringOfEquals("token_type","Bearer",False) <> True) Then
System.DebugLog("Expected a bearer access token; existing cache unchanged.")
Return
End If
Dim obtained As New Chilkat.CkDateTime
success = obtained.SetFromCurrentSystemTime()
If (success <> True) Then
System.DebugLog("Could not timestamp the access token.")
Return
End If
success = result.UpdateString("obtained_at",obtained.GetAsTimestamp(False))
// The transfer examples read host and access_token; these extra fields bind future refreshes.
success = result.UpdateString("host",sharepointHost)
success = result.UpdateString("tenant_id",tenantId)
success = result.UpdateString("client_id",clientId)
success = result.UpdateString("account_key",accountKey)
success = result.UpdateString("resource_scope",resourceScope)
success = fac.DirEnsureExists("qa_data/tokens")
If (success <> True) Then
System.DebugLog("Could not create the private cache directory.")
Return
End If
If (hadCache = True) Then
success = previous.WriteFile(backupPath)
If (success <> True) Then
System.DebugLog("Could not back up the previous cache; no replacement attempted.")
Return
End If
End If
success = result.WriteFile(cachePath)
If (success <> True) Then
System.DebugLog("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.
System.DebugLog("SharePoint token cache saved. The OneDrive transfer examples can now load it.")