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 AutoIt Downloads
Local $bSuccess = False
; Assumes Chilkat is unlocked. See Global Unlock Sample.
$bSuccess = False
; Run authorize once; change to refresh for subsequent unattended renewals.
Local $sAction = "authorize"
Local $sTenantId = "YOUR_TENANT_ID"
Local $sClientId = "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 $sAccountKey = "YOUR_LOCAL_ACCOUNT_KEY"
Local $sCachePath = "qa_data/tokens/oneDrive-sharepoint.json"
Local $sBackupPath = "qa_data/tokens/oneDrive-sharepoint.json.bak"
If (($sAction <> "authorize") And ($sAction <> "refresh")) Then
ConsoleWrite("Choose authorize or refresh." & @CRLF)
Exit
EndIf
$oHost = ObjCreate("Chilkat.StringBuilder")
$oHost.Append($sharepointHost)
$oMatch = ObjCreate("Chilkat.JsonObject")
Local $iMatched = $oHost.RegexMatch("(?i)\A[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.sharepoint\.com\z",$oMatch,100)
If ($iMatched <> 1) Then
ConsoleWrite("Set the trusted SharePoint hostname for this global-cloud example, without a scheme, path, or port." & @CRLF)
Exit
EndIf
; Use the organization's Directory (tenant) ID, not common, organizations, or consumers.
$oTenant = ObjCreate("Chilkat.StringBuilder")
$oTenant.Append($sTenantId)
$iMatched = $oTenant.RegexMatch("(?i)\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z",$oMatch,100)
If ($iMatched <> 1) Then
ConsoleWrite("Set the organization tenant GUID before running." & @CRLF)
Exit
EndIf
$oHttp = ObjCreate("Chilkat.Http")
$oHttp.RequireSslCertVerify = True
$oHttp.FollowRedirects = False
$oHttp.ConnectTimeout = 20
$oHttp.ReadTimeout = 30
$oTokenEndpoint = ObjCreate("Chilkat.StringBuilder")
$oTokenEndpoint.Append("https://login.microsoftonline.com/")
$oTokenEndpoint.Append($oHttp.UrlEncode($sTenantId))
$oTokenEndpoint.Append("/oauth2/v2.0/token")
$oAuthorizeEndpoint = ObjCreate("Chilkat.StringBuilder")
$oAuthorizeEndpoint.Append("https://login.microsoftonline.com/")
$oAuthorizeEndpoint.Append($oHttp.UrlEncode($sTenantId))
$oAuthorizeEndpoint.Append("/oauth2/v2.0/authorize")
$oScopeBuilder = ObjCreate("Chilkat.StringBuilder")
$oScopeBuilder.Append("https://")
$oScopeBuilder.Append($sharepointHost)
$oScopeBuilder.Append("/.default")
Local $sResourceScope = $oScopeBuilder.GetAsString()
$oFac = ObjCreate("Chilkat.FileAccess")
Local $bHadCache = $oFac.FileExists($sCachePath)
$oPrevious = ObjCreate("Chilkat.JsonObject")
$oPrevious.Strict = True
If ($bHadCache = True) Then
$bSuccess = $oPrevious.LoadFile($sCachePath)
If ($bSuccess <> True) Then
ConsoleWrite("Invalid existing cache; recover its private backup before continuing." & @CRLF)
Exit
EndIf
EndIf
$oResult = ObjCreate("Chilkat.JsonObject")
$oResult.Strict = True
If ($sAction = "authorize") Then
; Register http://localhost:3017/ as a Mobile and desktop applications redirect URI.
$oOauth = ObjCreate("Chilkat.OAuth2")
$oOauth.AuthorizationEndpoint = $oAuthorizeEndpoint.GetAsString()
$oOauth.TokenEndpoint = $oTokenEndpoint.GetAsString()
$oOauth.ClientId = $sClientId
$oOauth.LocalHost = "localhost"
$oOauth.ListenPort = 3017
$oOauth.CodeChallenge = True
$oOauth.CodeChallengeMethod = "S256"
; No client secret in a public desktop application.
$oScopes = ObjCreate("Chilkat.StringBuilder")
$oScopes.Append("offline_access ")
$oScopes.Append($sResourceScope)
$oOauth.Scope = $oScopes.GetAsString()
$bSuccess = $oOauth.AddAuthQueryParam("prompt","select_account")
If ($bSuccess <> True) Then
ConsoleWrite("Could not configure the authorization request." & @CRLF)
Exit
EndIf
Local $sAuthUrl = $oOauth.StartAuth()
If ($oOauth.LastMethodSuccess <> True) Then
ConsoleWrite("Could not start the local authorization listener." & @CRLF)
Exit
EndIf
$bSuccess = $oOauth.LaunchBrowser($sAuthUrl)
If ($bSuccess <> True) Then
$oOauth.Cancel()
ConsoleWrite("Could not open the system browser." & @CRLF)
Exit
EndIf
Local $iWaited = 0
While (($oOauth.AuthFlowState < 3) And ($iWaited < 180000))
$oOauth.SleepMs 200
$iWaited = $iWaited + 200
Wend
If ($oOauth.AuthFlowState < 3) Then
$oOauth.Cancel()
ConsoleWrite("Authorization timed out." & @CRLF)
Exit
EndIf
If ($oOauth.AuthFlowState <> 3) Then
ConsoleWrite("Authorization did not complete. Flow state: " & $oOauth.AuthFlowState & @CRLF)
Exit
EndIf
$bSuccess = $oResult.Load($oOauth.AccessTokenResponse)
If ($bSuccess <> True) Then
ConsoleWrite("Invalid token response; existing cache unchanged." & @CRLF)
Exit
EndIf
If (($oResult.JsonTypeOf("refresh_token") <> 1) Or ($oResult.StringOfEquals("refresh_token","",True) = True)) Then
ConsoleWrite("Expected a nonempty refresh_token in the JSON." & @CRLF)
Exit
EndIf
Else
If ($bHadCache <> True) Then
ConsoleWrite("No SharePoint token cache. Run authorize first." & @CRLF)
Exit
EndIf
If ($oPrevious.StringOfEquals("host",$sharepointHost,True) <> True) Then
ConsoleWrite("Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache." & @CRLF)
Exit
EndIf
If ($oPrevious.StringOfEquals("tenant_id",$sTenantId,True) <> True) Then
ConsoleWrite("Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache." & @CRLF)
Exit
EndIf
If ($oPrevious.StringOfEquals("client_id",$sClientId,True) <> True) Then
ConsoleWrite("Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache." & @CRLF)
Exit
EndIf
If ($oPrevious.StringOfEquals("account_key",$sAccountKey,True) <> True) Then
ConsoleWrite("Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache." & @CRLF)
Exit
EndIf
If ($oPrevious.StringOfEquals("resource_scope",$sResourceScope,True) <> True) Then
ConsoleWrite("Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache." & @CRLF)
Exit
EndIf
If (($oPrevious.JsonTypeOf("refresh_token") <> 1) Or ($oPrevious.StringOfEquals("refresh_token","",True) = True)) Then
ConsoleWrite("Expected a nonempty refresh_token in the JSON." & @CRLF)
Exit
EndIf
$oReq = ObjCreate("Chilkat.HttpRequest")
$oReq.HttpVerb = "POST"
$oReq.ContentType = "application/x-www-form-urlencoded"
$oReq.AddParam "client_id",$sClientId
$oReq.AddParam "grant_type","refresh_token"
$oReq.AddParam "refresh_token",$oPrevious.StringOf("refresh_token")
; Explicit resource scope keeps the renewal on SharePoint, not Microsoft Graph.
$oReq.AddParam "scope",$sResourceScope
$oResp = ObjCreate("Chilkat.HttpResponse")
$bSuccess = $oHttp.HttpReq($oTokenEndpoint.GetAsString(),$oReq,$oResp)
If (($bSuccess <> True) And ($oResp.StatusCode = 0)) Then
ConsoleWrite("No token response received; existing cache unchanged." & @CRLF)
Exit
EndIf
If ($oResp.StatusCode <> 200) Then
ConsoleWrite("Token renewal failed. HTTP status: " & $oResp.StatusCode & @CRLF)
If ($oResp.StatusCode = 429) Then
ConsoleWrite("Retry-After: " & $oResp.GetHeaderField("Retry-After") & @CRLF)
EndIf
ConsoleWrite("Check consent and token validity. If interaction is required, run authorize deliberately." & @CRLF)
Exit
EndIf
If ($bSuccess <> True) Then
ConsoleWrite("Token response did not complete; existing cache unchanged." & @CRLF)
Exit
EndIf
$bSuccess = $oResult.Load($oResp.BodyStr)
If ($bSuccess <> True) Then
ConsoleWrite("Invalid refresh response; existing cache unchanged." & @CRLF)
Exit
EndIf
If ($oResult.JsonTypeOf("refresh_token") = -1) Then
$oResult.UpdateString("refresh_token",$oPrevious.StringOf("refresh_token"))
Else
If (($oResult.JsonTypeOf("refresh_token") <> 1) Or ($oResult.StringOfEquals("refresh_token","",True) = True)) Then
ConsoleWrite("Expected a nonempty refresh_token in the JSON." & @CRLF)
Exit
EndIf
EndIf
EndIf
If (($oResult.JsonTypeOf("access_token") <> 1) Or ($oResult.StringOfEquals("access_token","",True) = True)) Then
ConsoleWrite("Expected a nonempty access_token in the JSON." & @CRLF)
Exit
EndIf
If (($oResult.JsonTypeOf("expires_in") <> 2) Or ($oResult.IntOf("expires_in") <= 0)) Then
ConsoleWrite("Expected a positive access-token lifetime; existing cache unchanged." & @CRLF)
Exit
EndIf
If ($oResult.StringOfEquals("token_type","Bearer",False) <> True) Then
ConsoleWrite("Expected a bearer access token; existing cache unchanged." & @CRLF)
Exit
EndIf
$oObtained = ObjCreate("Chilkat.CkDateTime")
$bSuccess = $oObtained.SetFromCurrentSystemTime()
If ($bSuccess <> True) Then
ConsoleWrite("Could not timestamp the access token." & @CRLF)
Exit
EndIf
$oResult.UpdateString("obtained_at",$oObtained.GetAsTimestamp(False))
; The transfer examples read host and access_token; these extra fields bind future refreshes.
$oResult.UpdateString("host",$sharepointHost)
$oResult.UpdateString("tenant_id",$sTenantId)
$oResult.UpdateString("client_id",$sClientId)
$oResult.UpdateString("account_key",$sAccountKey)
$oResult.UpdateString("resource_scope",$sResourceScope)
$bSuccess = $oFac.DirEnsureExists("qa_data/tokens")
If ($bSuccess <> True) Then
ConsoleWrite("Could not create the private cache directory." & @CRLF)
Exit
EndIf
If ($bHadCache = True) Then
$bSuccess = $oPrevious.WriteFile($sBackupPath)
If ($bSuccess <> True) Then
ConsoleWrite("Could not back up the previous cache; no replacement attempted." & @CRLF)
Exit
EndIf
EndIf
$bSuccess = $oResult.WriteFile($sCachePath)
If ($bSuccess <> True) Then
ConsoleWrite("Could not save the new cache; recover the private backup if an older cache existed." & @CRLF)
Exit
EndIf
; Never print the tokens, token response, or authorization URL.
ConsoleWrite("SharePoint token cache saved. The OneDrive transfer examples can now load it." & @CRLF)