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 Lua Downloads
local chilkat = require("chilkat")
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false
-- Run authorize once; change to refresh for subsequent unattended renewals.
local action = "authorize"
local tenantId = "YOUR_TENANT_ID"
local 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.
local sharepointHost = "YOUR_TENANT.sharepoint.com"
-- An application-defined key for this user/account, not an access token or password.
local accountKey = "YOUR_LOCAL_ACCOUNT_KEY"
local cachePath = "qa_data/tokens/oneDrive-sharepoint.json"
local backupPath = "qa_data/tokens/oneDrive-sharepoint.json.bak"
if (action ~= "authorize") and (action ~= "refresh") then
print("Choose authorize or refresh.")
return
end
local host = chilkat.StringBuilder.new()
host:append(sharepointHost)
local match = chilkat.JsonObject.new()
local matched = host:regex_match("(?i)\\A[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.sharepoint\\.com\\z", match, 100)
if matched ~= 1 then
print("Set the trusted SharePoint hostname for this global-cloud example, without a scheme, path, or port.")
return
end
-- Use the organization's Directory (tenant) ID, not common, organizations, or consumers.
local tenant = chilkat.StringBuilder.new()
tenant:append(tenantId)
matched = tenant:regex_match("(?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
print("Set the organization tenant GUID before running.")
return
end
local http = chilkat.Http.new()
http.require_ssl_cert_verify = true
http.follow_redirects = false
http.connect_timeout = 20
http.read_timeout = 30
local tokenEndpoint = chilkat.StringBuilder.new()
tokenEndpoint:append("https://login.microsoftonline.com/")
tokenEndpoint:append(http:url_encode(tenantId))
tokenEndpoint:append("/oauth2/v2.0/token")
local authorizeEndpoint = chilkat.StringBuilder.new()
authorizeEndpoint:append("https://login.microsoftonline.com/")
authorizeEndpoint:append(http:url_encode(tenantId))
authorizeEndpoint:append("/oauth2/v2.0/authorize")
local scopeBuilder = chilkat.StringBuilder.new()
scopeBuilder:append("https://")
scopeBuilder:append(sharepointHost)
scopeBuilder:append("/.default")
local resourceScope = scopeBuilder:get_as_string()
local fac = chilkat.FileAccess.new()
local hadCache = fac:file_exists(cachePath)
local previous = chilkat.JsonObject.new()
previous.strict = true
if hadCache then
success = previous:load_file(cachePath)
if not success then
print("Invalid existing cache; recover its private backup before continuing.")
return
end
end
local result = chilkat.JsonObject.new()
result.strict = true
if action == "authorize" then
-- Register http://localhost:3017/ as a Mobile and desktop applications redirect URI.
local oauth = chilkat.OAuth2.new()
oauth.authorization_endpoint = authorizeEndpoint:get_as_string()
oauth.token_endpoint = tokenEndpoint:get_as_string()
oauth.client_id = clientId
oauth.local_host = "localhost"
oauth.listen_port = 3017
oauth.code_challenge = true
oauth.code_challenge_method = "S256"
-- No client secret in a public desktop application.
local scopes = chilkat.StringBuilder.new()
scopes:append("offline_access ")
scopes:append(resourceScope)
oauth.scope = scopes:get_as_string()
success = oauth:add_auth_query_param("prompt", "select_account")
if not success then
print("Could not configure the authorization request.")
return
end
local authUrl = oauth:start_auth()
if not oauth.last_method_success then
print("Could not start the local authorization listener.")
return
end
success = oauth:launch_browser(authUrl)
if not success then
oauth:cancel()
print("Could not open the system browser.")
return
end
local waited = 0
while (oauth.auth_flow_state < 3) and (waited < 180000) do
oauth:sleep_ms(200)
waited = waited + 200
end
if oauth.auth_flow_state < 3 then
oauth:cancel()
print("Authorization timed out.")
return
end
if oauth.auth_flow_state ~= 3 then
print("Authorization did not complete. Flow state: " .. oauth.auth_flow_state)
return
end
success = result:load(oauth.access_token_response)
if not success then
print("Invalid token response; existing cache unchanged.")
return
end
if (result:json_type_of("refresh_token") ~= 1) or (result:string_of_equals("refresh_token", "", true)) then
print("Expected a nonempty refresh_token in the JSON.")
return
end
else
if not hadCache then
print("No SharePoint token cache. Run authorize first.")
return
end
if not previous:string_of_equals("host", sharepointHost, true) then
print("Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.")
return
end
if not previous:string_of_equals("tenant_id", tenantId, true) then
print("Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.")
return
end
if not previous:string_of_equals("client_id", clientId, true) then
print("Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.")
return
end
if not previous:string_of_equals("account_key", accountKey, true) then
print("Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.")
return
end
if not previous:string_of_equals("resource_scope", resourceScope, true) then
print("Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.")
return
end
if (previous:json_type_of("refresh_token") ~= 1) or (previous:string_of_equals("refresh_token", "", true)) then
print("Expected a nonempty refresh_token in the JSON.")
return
end
local req = chilkat.HttpRequest.new()
req.http_verb = "POST"
req.content_type = "application/x-www-form-urlencoded"
req:add_param("client_id", clientId)
req:add_param("grant_type", "refresh_token")
req:add_param("refresh_token", previous:string_of("refresh_token"))
-- Explicit resource scope keeps the renewal on SharePoint, not Microsoft Graph.
req:add_param("scope", resourceScope)
local resp = chilkat.HttpResponse.new()
success = http:http_req(tokenEndpoint:get_as_string(), req, resp)
if (not success) and (resp.status_code == 0) then
print("No token response received; existing cache unchanged.")
return
end
if resp.status_code ~= 200 then
print("Token renewal failed. HTTP status: " .. resp.status_code)
if resp.status_code == 429 then
print("Retry-After: " .. resp:get_header_field("Retry-After"))
end
print("Check consent and token validity. If interaction is required, run authorize deliberately.")
return
end
if not success then
print("Token response did not complete; existing cache unchanged.")
return
end
success = result:load(resp.body_str)
if not success then
print("Invalid refresh response; existing cache unchanged.")
return
end
if result:json_type_of("refresh_token") == (-1) then
result:update_string("refresh_token", previous:string_of("refresh_token"))
elseif (result:json_type_of("refresh_token") ~= 1) or (result:string_of_equals("refresh_token", "", true)) then
print("Expected a nonempty refresh_token in the JSON.")
return
end
end
if (result:json_type_of("access_token") ~= 1) or (result:string_of_equals("access_token", "", true)) then
print("Expected a nonempty access_token in the JSON.")
return
end
if (result:json_type_of("expires_in") ~= 2) or (result:int_of("expires_in") <= 0) then
print("Expected a positive access-token lifetime; existing cache unchanged.")
return
end
if not result:string_of_equals("token_type", "Bearer", false) then
print("Expected a bearer access token; existing cache unchanged.")
return
end
local obtained = chilkat.DateTime.new()
success = obtained:set_from_current_system_time()
if not success then
print("Could not timestamp the access token.")
return
end
result:update_string("obtained_at", obtained:get_as_timestamp(false))
-- The transfer examples read host and access_token; these extra fields bind future refreshes.
result:update_string("host", sharepointHost)
result:update_string("tenant_id", tenantId)
result:update_string("client_id", clientId)
result:update_string("account_key", accountKey)
result:update_string("resource_scope", resourceScope)
success = fac:dir_ensure_exists("qa_data/tokens")
if not success then
print("Could not create the private cache directory.")
return
end
if hadCache then
success = previous:write_file(backupPath)
if not success then
print("Could not back up the previous cache; no replacement attempted.")
return
end
end
success = result:write_file(cachePath)
if not success then
print("Could not save the new cache; recover the private backup if an older cache existed.")
return
end
-- Never print the tokens, token response, or authorization URL.
print("SharePoint token cache saved. The OneDrive transfer examples can now load it.")