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 Swift Downloads
func chilkatTest() {
var success: Bool = false
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success = false
// Run authorize once; change to refresh for subsequent unattended renewals.
var action: String? = "authorize"
var tenantId: String? = "YOUR_TENANT_ID"
var clientId: 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.
var sharepointHost: String? = "YOUR_TENANT.sharepoint.com"
// An application-defined key for this user/account, not an access token or password.
var accountKey: String? = "YOUR_LOCAL_ACCOUNT_KEY"
var cachePath: String? = "qa_data/tokens/oneDrive-sharepoint.json"
var backupPath: String? = "qa_data/tokens/oneDrive-sharepoint.json.bak"
if (action != "authorize") && (action != "refresh") {
print("Choose authorize or refresh.")
return
}
let host = CkoStringBuilder()!
host.append(value: sharepointHost)
let match = CkoJsonObject()!
var matched: Int = host.regexMatch(pattern: "(?i)\\A[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.sharepoint\\.com\\z", json: match, timeoutMs: 100).intValue
if matched != 1 {
print("Set the trusted SharePoint hostname for this global-cloud example, without a scheme, path, or port.")
return
}
// Use the organization's Directory (tenant) ID, not common, organizations, or consumers.
let tenant = CkoStringBuilder()!
tenant.append(value: tenantId)
matched = tenant.regexMatch(pattern: "(?i)\\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\z", json: match, timeoutMs: 100).intValue
if matched != 1 {
print("Set the organization tenant GUID before running.")
return
}
let http = CkoHttp()!
http.requireSslCertVerify = true
http.followRedirects = false
http.connectTimeout = 20
http.readTimeout = 30
let tokenEndpoint = CkoStringBuilder()!
tokenEndpoint.append(value: "https://login.microsoftonline.com/")
tokenEndpoint.append(value: http.urlEncode(str: tenantId))
tokenEndpoint.append(value: "/oauth2/v2.0/token")
let authorizeEndpoint = CkoStringBuilder()!
authorizeEndpoint.append(value: "https://login.microsoftonline.com/")
authorizeEndpoint.append(value: http.urlEncode(str: tenantId))
authorizeEndpoint.append(value: "/oauth2/v2.0/authorize")
let scopeBuilder = CkoStringBuilder()!
scopeBuilder.append(value: "https://")
scopeBuilder.append(value: sharepointHost)
scopeBuilder.append(value: "/.default")
var resourceScope: String? = scopeBuilder.getAsString()
let fac = CkoFileAccess()!
var hadCache: Bool = fac.fileExists(path: cachePath)
let previous = CkoJsonObject()!
previous.strict = true
if hadCache == true {
success = previous.loadFile(path: cachePath)
if success != true {
print("Invalid existing cache; recover its private backup before continuing.")
return
}
}
let result = CkoJsonObject()!
result.strict = true
if action == "authorize" {
// Register http://localhost:3017/ as a Mobile and desktop applications redirect URI.
let oauth = CkoOAuth2()!
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.
let scopes = CkoStringBuilder()!
scopes.append(value: "offline_access ")
scopes.append(value: resourceScope)
oauth.scope = scopes.getAsString()
success = oauth.addAuthQueryParam(name: "prompt", value: "select_account")
if success != true {
print("Could not configure the authorization request.")
return
}
var authUrl: String? = oauth.startAuth()
if oauth.lastMethodSuccess != true {
print("Could not start the local authorization listener.")
return
}
success = oauth.launchBrowser(url: authUrl)
if success != true {
oauth.cancel()
print("Could not open the system browser.")
return
}
var waited: Int = 0
while ((oauth.authFlowState.intValue < 3) && (waited < 180000)) {
oauth.sleepMs(millisec: 200)
waited = waited + 200
}
if oauth.authFlowState.intValue < 3 {
oauth.cancel()
print("Authorization timed out.")
return
}
if oauth.authFlowState.intValue != 3 {
print("Authorization did not complete. Flow state: \(oauth.authFlowState.intValue)")
return
}
success = result.load(json: oauth.accessTokenResponse)
if success != true {
print("Invalid token response; existing cache unchanged.")
return
}
if (result.jsonType(of: "refresh_token").intValue != 1) || (result.string(ofEquals: "refresh_token", value: "", caseSensitive: true) == true) {
print("Expected a nonempty refresh_token in the JSON.")
return
}
}
else {
if hadCache != true {
print("No SharePoint token cache. Run authorize first.")
return
}
if previous.string(ofEquals: "host", value: sharepointHost, caseSensitive: true) != true {
print("Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.")
return
}
if previous.string(ofEquals: "tenant_id", value: tenantId, caseSensitive: true) != true {
print("Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.")
return
}
if previous.string(ofEquals: "client_id", value: clientId, caseSensitive: true) != true {
print("Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.")
return
}
if previous.string(ofEquals: "account_key", value: accountKey, caseSensitive: true) != true {
print("Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.")
return
}
if previous.string(ofEquals: "resource_scope", value: resourceScope, caseSensitive: true) != true {
print("Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.")
return
}
if (previous.jsonType(of: "refresh_token").intValue != 1) || (previous.string(ofEquals: "refresh_token", value: "", caseSensitive: true) == true) {
print("Expected a nonempty refresh_token in the JSON.")
return
}
let req = CkoHttpRequest()!
req.httpVerb = "POST"
req.contentType = "application/x-www-form-urlencoded"
req.addParam(name: "client_id", value: clientId)
req.addParam(name: "grant_type", value: "refresh_token")
req.addParam(name: "refresh_token", value: previous.string(of: "refresh_token"))
// Explicit resource scope keeps the renewal on SharePoint, not Microsoft Graph.
req.addParam(name: "scope", value: resourceScope)
let resp = CkoHttpResponse()!
success = http.httpReq(url: tokenEndpoint.getAsString(), request: req, response: resp)
if (success != true) && (resp.statusCode.intValue == 0) {
print("No token response received; existing cache unchanged.")
return
}
if resp.statusCode.intValue != 200 {
print("Token renewal failed. HTTP status: \(resp.statusCode.intValue)")
if resp.statusCode.intValue == 429 {
print("Retry-After: \(resp.getHeaderField(fieldName: "Retry-After")!)")
}
print("Check consent and token validity. If interaction is required, run authorize deliberately.")
return
}
if success != true {
print("Token response did not complete; existing cache unchanged.")
return
}
success = result.load(json: resp.bodyStr)
if success != true {
print("Invalid refresh response; existing cache unchanged.")
return
}
if result.jsonType(of: "refresh_token").intValue == -1 {
result.updateString(jsonPath: "refresh_token", value: previous.string(of: "refresh_token"))
}
else {
if (result.jsonType(of: "refresh_token").intValue != 1) || (result.string(ofEquals: "refresh_token", value: "", caseSensitive: true) == true) {
print("Expected a nonempty refresh_token in the JSON.")
return
}
}
}
if (result.jsonType(of: "access_token").intValue != 1) || (result.string(ofEquals: "access_token", value: "", caseSensitive: true) == true) {
print("Expected a nonempty access_token in the JSON.")
return
}
if (result.jsonType(of: "expires_in").intValue != 2) || (result.int(of: "expires_in").intValue <= 0) {
print("Expected a positive access-token lifetime; existing cache unchanged.")
return
}
if result.string(ofEquals: "token_type", value: "Bearer", caseSensitive: false) != true {
print("Expected a bearer access token; existing cache unchanged.")
return
}
let obtained = CkoDateTime()!
success = obtained.setFromCurrentSystemTime()
if success != true {
print("Could not timestamp the access token.")
return
}
result.updateString(jsonPath: "obtained_at", value: obtained.get(asTimestamp: false))
// The transfer examples read host and access_token; these extra fields bind future refreshes.
result.updateString(jsonPath: "host", value: sharepointHost)
result.updateString(jsonPath: "tenant_id", value: tenantId)
result.updateString(jsonPath: "client_id", value: clientId)
result.updateString(jsonPath: "account_key", value: accountKey)
result.updateString(jsonPath: "resource_scope", value: resourceScope)
success = fac.dirEnsureExists(dirPath: "qa_data/tokens")
if success != true {
print("Could not create the private cache directory.")
return
}
if hadCache == true {
success = previous.writeFile(path: backupPath)
if success != true {
print("Could not back up the previous cache; no replacement attempted.")
return
}
}
success = result.writeFile(path: cachePath)
if success != true {
print("Could not save the new cache; recover the private backup if an older cache existed.")
return
}
// Never print the tokens, token response, or authorization URL.
print("SharePoint token cache saved. The OneDrive transfer examples can now load it.")
}