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 Lazarus Pascal Downloads
program ChilkatDemo;
// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
SysUtils,
CkDllLoader,
Chilkat.CkDateTime,
Chilkat.HttpRequest,
Chilkat.HttpResponse,
Chilkat.OAuth2,
Chilkat.FileAccess,
Chilkat.JsonObject,
Chilkat.StringBuilder,
Chilkat.Http;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
action: string;
tenantId: string;
clientId: string;
sharepointHost: string;
accountKey: string;
cachePath: string;
backupPath: string;
host: TStringBuilder;
match: TJsonObject;
matched: Integer;
tenant: TStringBuilder;
http: THttp;
tokenEndpoint: TStringBuilder;
authorizeEndpoint: TStringBuilder;
scopeBuilder: TStringBuilder;
resourceScope: string;
fac: TFileAccess;
hadCache: Boolean;
previous: TJsonObject;
result: TJsonObject;
oauth: TOAuth2;
scopes: TStringBuilder;
authUrl: string;
waited: Integer;
req: THttpRequest;
resp: THttpResponse;
obtained: TCkDateTime;
begin
success := False;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success := False;
// Run authorize once; change to refresh for subsequent unattended renewals.
action := 'authorize';
tenantId := 'YOUR_TENANT_ID';
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.
sharepointHost := 'YOUR_TENANT.sharepoint.com';
// An application-defined key for this user/account, not an access token or password.
accountKey := 'YOUR_LOCAL_ACCOUNT_KEY';
cachePath := 'qa_data/tokens/oneDrive-sharepoint.json';
backupPath := 'qa_data/tokens/oneDrive-sharepoint.json.bak';
if ((action <> 'authorize') and (action <> 'refresh')) then
begin
WriteLn('Choose authorize or refresh.');
Exit;
end;
host := TStringBuilder.Create;
host.Append(sharepointHost);
match := TJsonObject.Create;
matched := host.RegexMatch('(?i)\A[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.sharepoint\.com\z',match,100);
if (matched <> 1) then
begin
WriteLn('Set the trusted SharePoint hostname for this global-cloud example, without a scheme, path, or port.');
Exit;
end;
// Use the organization's Directory (tenant) ID, not common, organizations, or consumers.
tenant := TStringBuilder.Create;
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
begin
WriteLn('Set the organization tenant GUID before running.');
Exit;
end;
http := THttp.Create;
http.RequireSslCertVerify := True;
http.FollowRedirects := False;
http.ConnectTimeout := 20;
http.ReadTimeout := 30;
tokenEndpoint := TStringBuilder.Create;
tokenEndpoint.Append('https://login.microsoftonline.com/');
tokenEndpoint.Append(http.UrlEncode(tenantId));
tokenEndpoint.Append('/oauth2/v2.0/token');
authorizeEndpoint := TStringBuilder.Create;
authorizeEndpoint.Append('https://login.microsoftonline.com/');
authorizeEndpoint.Append(http.UrlEncode(tenantId));
authorizeEndpoint.Append('/oauth2/v2.0/authorize');
scopeBuilder := TStringBuilder.Create;
scopeBuilder.Append('https://');
scopeBuilder.Append(sharepointHost);
scopeBuilder.Append('/.default');
resourceScope := scopeBuilder.GetAsString();
fac := TFileAccess.Create;
hadCache := fac.FileExists(cachePath);
previous := TJsonObject.Create;
previous.Strict := True;
if (hadCache = True) then
begin
success := previous.LoadFile(cachePath);
if (success <> True) then
begin
WriteLn('Invalid existing cache; recover its private backup before continuing.');
Exit;
end;
end;
result := TJsonObject.Create;
result.Strict := True;
if (action = 'authorize') then
begin
// Register http://localhost:3017/ as a Mobile and desktop applications redirect URI.
oauth := TOAuth2.Create;
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.
scopes := TStringBuilder.Create;
scopes.Append('offline_access ');
scopes.Append(resourceScope);
oauth.Scope := scopes.GetAsString();
success := oauth.AddAuthQueryParam('prompt','select_account');
if (success <> True) then
begin
WriteLn('Could not configure the authorization request.');
Exit;
end;
authUrl := oauth.StartAuth();
if (oauth.LastMethodSuccess <> True) then
begin
WriteLn('Could not start the local authorization listener.');
Exit;
end;
success := oauth.LaunchBrowser(authUrl);
if (success <> True) then
begin
oauth.Cancel();
WriteLn('Could not open the system browser.');
Exit;
end;
waited := 0;
while ((oauth.AuthFlowState < 3) and (waited < 180000)) do
begin
oauth.SleepMs(200);
waited := waited + 200;
end;
if (oauth.AuthFlowState < 3) then
begin
oauth.Cancel();
WriteLn('Authorization timed out.');
Exit;
end;
if (oauth.AuthFlowState <> 3) then
begin
WriteLn('Authorization did not complete. Flow state: ' + oauth.AuthFlowState);
Exit;
end;
success := result.Load(oauth.AccessTokenResponse);
if (success <> True) then
begin
WriteLn('Invalid token response; existing cache unchanged.');
Exit;
end;
if ((result.JsonTypeOf('refresh_token') <> 1) or (result.StringOfEquals('refresh_token','',True) = True)) then
begin
WriteLn('Expected a nonempty refresh_token in the JSON.');
Exit;
end;
end
else
begin
if (hadCache <> True) then
begin
WriteLn('No SharePoint token cache. Run authorize first.');
Exit;
end;
if (previous.StringOfEquals('host',sharepointHost,True) <> True) then
begin
WriteLn('Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.');
Exit;
end;
if (previous.StringOfEquals('tenant_id',tenantId,True) <> True) then
begin
WriteLn('Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.');
Exit;
end;
if (previous.StringOfEquals('client_id',clientId,True) <> True) then
begin
WriteLn('Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.');
Exit;
end;
if (previous.StringOfEquals('account_key',accountKey,True) <> True) then
begin
WriteLn('Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.');
Exit;
end;
if (previous.StringOfEquals('resource_scope',resourceScope,True) <> True) then
begin
WriteLn('Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.');
Exit;
end;
if ((previous.JsonTypeOf('refresh_token') <> 1) or (previous.StringOfEquals('refresh_token','',True) = True)) then
begin
WriteLn('Expected a nonempty refresh_token in the JSON.');
Exit;
end;
req := THttpRequest.Create;
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);
resp := THttpResponse.Create;
success := http.HttpReq(tokenEndpoint.GetAsString(),req,resp);
if ((success <> True) and (resp.StatusCode = 0)) then
begin
WriteLn('No token response received; existing cache unchanged.');
Exit;
end;
if (resp.StatusCode <> 200) then
begin
WriteLn('Token renewal failed. HTTP status: ' + resp.StatusCode);
if (resp.StatusCode = 429) then
begin
WriteLn('Retry-After: ' + resp.GetHeaderField('Retry-After'));
end;
WriteLn('Check consent and token validity. If interaction is required, run authorize deliberately.');
Exit;
end;
if (success <> True) then
begin
WriteLn('Token response did not complete; existing cache unchanged.');
Exit;
end;
success := result.Load(resp.BodyStr);
if (success <> True) then
begin
WriteLn('Invalid refresh response; existing cache unchanged.');
Exit;
end;
if (result.JsonTypeOf('refresh_token') = -1) then
begin
result.UpdateString('refresh_token',previous.StringOf('refresh_token'));
end
else
begin
if ((result.JsonTypeOf('refresh_token') <> 1) or (result.StringOfEquals('refresh_token','',True) = True)) then
begin
WriteLn('Expected a nonempty refresh_token in the JSON.');
Exit;
end;
end;
end;
if ((result.JsonTypeOf('access_token') <> 1) or (result.StringOfEquals('access_token','',True) = True)) then
begin
WriteLn('Expected a nonempty access_token in the JSON.');
Exit;
end;
if ((result.JsonTypeOf('expires_in') <> 2) or (result.IntOf('expires_in') <= 0)) then
begin
WriteLn('Expected a positive access-token lifetime; existing cache unchanged.');
Exit;
end;
if (result.StringOfEquals('token_type','Bearer',False) <> True) then
begin
WriteLn('Expected a bearer access token; existing cache unchanged.');
Exit;
end;
obtained := TCkDateTime.Create;
success := obtained.SetFromCurrentSystemTime();
if (success <> True) then
begin
WriteLn('Could not timestamp the access token.');
Exit;
end;
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
begin
WriteLn('Could not create the private cache directory.');
Exit;
end;
if (hadCache = True) then
begin
success := previous.WriteFile(backupPath);
if (success <> True) then
begin
WriteLn('Could not back up the previous cache; no replacement attempted.');
Exit;
end;
end;
success := result.WriteFile(cachePath);
if (success <> True) then
begin
WriteLn('Could not save the new cache; recover the private backup if an older cache existed.');
Exit;
end;
// Never print the tokens, token response, or authorization URL.
WriteLn('SharePoint token cache saved. The OneDrive transfer examples can now load it.');
host.Free;
match.Free;
tenant.Free;
http.Free;
tokenEndpoint.Free;
authorizeEndpoint.Free;
scopeBuilder.Free;
fac.Free;
previous.Free;
result.Free;
oauth.Free;
scopes.Free;
req.Free;
resp.Free;
obtained.Free;
end;
// ---------------------------------------------------------------------------
begin
try
RunDemo;
except
on E: Exception do
WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
end;
WriteLn;
{$IFDEF MSWINDOWS}
WriteLn('Press Enter to exit...');
ReadLn;
{$ENDIF}
end.