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

VB.NET
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
    Debug.WriteLine("Choose authorize or refresh.")
    Exit Sub
End If

Dim host As New Chilkat.StringBuilder
host.Append(sharepointHost)
Dim match As New Chilkat.JsonObject
Dim matched As Integer = host.RegexMatch("(?i)\A[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.sharepoint\.com\z",match,100)
If (matched <> 1) Then
    Debug.WriteLine("Set the trusted SharePoint hostname for this global-cloud example, without a scheme, path, or port.")
    Exit Sub
End If

'  Use the organization's Directory (tenant) ID, not common, organizations, or consumers.
Dim tenant As New Chilkat.StringBuilder
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
    Debug.WriteLine("Set the organization tenant GUID before running.")
    Exit Sub
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
tokenEndpoint.Append("https://login.microsoftonline.com/")
tokenEndpoint.Append(http.UrlEncode(tenantId))
tokenEndpoint.Append("/oauth2/v2.0/token")
Dim authorizeEndpoint As New Chilkat.StringBuilder
authorizeEndpoint.Append("https://login.microsoftonline.com/")
authorizeEndpoint.Append(http.UrlEncode(tenantId))
authorizeEndpoint.Append("/oauth2/v2.0/authorize")
Dim scopeBuilder As New Chilkat.StringBuilder
scopeBuilder.Append("https://")
scopeBuilder.Append(sharepointHost)
scopeBuilder.Append("/.default")
Dim resourceScope As String = scopeBuilder.GetAsString()
Dim fac As New Chilkat.FileAccess
Dim hadCache As Boolean = fac.FileExists(cachePath)
Dim previous As New Chilkat.JsonObject
previous.Strict = True
If (hadCache = True) Then
    success = previous.LoadFile(cachePath)
    If (success <> True) Then
        Debug.WriteLine("Invalid existing cache; recover its private backup before continuing.")
        Exit Sub
    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
    scopes.Append("offline_access ")
    scopes.Append(resourceScope)
    oauth.Scope = scopes.GetAsString()
    success = oauth.AddAuthQueryParam("prompt","select_account")
    If (success <> True) Then
        Debug.WriteLine("Could not configure the authorization request.")
        Exit Sub
    End If

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

    success = oauth.LaunchBrowser(authUrl)
    If (success <> True) Then
        oauth.Cancel()
        Debug.WriteLine("Could not open the system browser.")
        Exit Sub
    End If

    Dim waited As Integer = 0
    While ((oauth.AuthFlowState < 3) And (waited < 180000))
        oauth.SleepMs(200)
        waited = waited + 200
    End While
    If (oauth.AuthFlowState < 3) Then
        oauth.Cancel()
        Debug.WriteLine("Authorization timed out.")
        Exit Sub
    End If

    If (oauth.AuthFlowState <> 3) Then
        Debug.WriteLine("Authorization did not complete. Flow state: " & oauth.AuthFlowState)
        Exit Sub
    End If

    success = result.Load(oauth.AccessTokenResponse)
    If (success <> True) Then
        Debug.WriteLine("Invalid token response; existing cache unchanged.")
        Exit Sub
    End If

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

Else
    If (hadCache <> True) Then
        Debug.WriteLine("No SharePoint token cache. Run authorize first.")
        Exit Sub
    End If

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

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

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

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

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

    If ((previous.JsonTypeOf("refresh_token") <> 1) Or (previous.StringOfEquals("refresh_token","",True) = True)) Then
        Debug.WriteLine("Expected a nonempty refresh_token in the JSON.")
        Exit Sub
    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
        Debug.WriteLine("No token response received; existing cache unchanged.")
        Exit Sub
    End If

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

        Debug.WriteLine("Check consent and token validity. If interaction is required, run authorize deliberately.")
        Exit Sub
    End If

    If (success <> True) Then
        Debug.WriteLine("Token response did not complete; existing cache unchanged.")
        Exit Sub
    End If

    success = result.Load(resp.BodyStr)
    If (success <> True) Then
        Debug.WriteLine("Invalid refresh response; existing cache unchanged.")
        Exit Sub
    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
            Debug.WriteLine("Expected a nonempty refresh_token in the JSON.")
            Exit Sub
        End If

    End If

End If

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

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

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

Dim obtained As New Chilkat.CkDateTime
success = obtained.SetFromCurrentSystemTime()
If (success <> True) Then
    Debug.WriteLine("Could not timestamp the access token.")
    Exit Sub
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
    Debug.WriteLine("Could not create the private cache directory.")
    Exit Sub
End If

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

End If

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

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