OneDrive: Access Microsoft 365 OneDrive with a Certificate
See more OneDrive Examples
Acquire an application token using an RSA certificate and list a selected organizational user's drives. This is for OneDrive for Business and SharePoint, not personal Microsoft accounts. Configure Graph application Files.Read.All and administrator consent for this listing. Provision the user's OneDrive separately; consent does not create it. Use an appropriate restricted-access design when broad application access is unnecessary.
Private onedrive-certificate-app.json contains tenant_id, client_id, user_id (object ID or UPN), pfx_path, and pfx_password. Upload the public certificate to the Entra application and protect the RSA private key in an environment you control. Use a tenant-specific authority. Never distribute this private key in a public application.
The five-minute PS256 assertion includes x5t#S256, the SHA-256 certificate thumbprint. It is sent only to the token endpoint. The resulting Graph token is sent to Graph. .default selects configured application permissions; no refresh token is issued. Acquire a new token with a fresh assertion before expiry.
Follows complete @odata.nextLink URLs, including after empty pages. It validates the Graph host/API path, rejects repeated links, and reports a stop at the demonstration bound of 100 pages. $top is page size, not the total result count. Enumeration is not a transactionally consistent snapshot during concurrent changes.
Permission: Application Files.Read.All with administrator consent.
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.Crypt2,
Chilkat.Jwt,
Chilkat.StringBuilder,
Chilkat.JsonObject,
Chilkat.PrivateKey,
Chilkat.HttpResponse,
Chilkat.HttpRequest,
Chilkat.Cert,
Chilkat.StringArray,
Chilkat.Http,
Chilkat.BinData;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
config: TJsonObject;
http: THttp;
tokenEndpoint: TStringBuilder;
tokenUrl: string;
cert: TCert;
key: TPrivateKey;
der: TBinData;
crypt: TCrypt2;
thumbprint: string;
header: TJsonObject;
claims: TJsonObject;
assertionId: string;
clock: TCkDateTime;
jwt: TJwt;
assertion: string;
req: THttpRequest;
resp: THttpResponse;
result: TJsonObject;
endpoint: TStringBuilder;
url: string;
nextLink: TStringBuilder;
seenLinks: TStringArray;
pageCount: Integer;
i: Integer;
nextType: Integer;
begin
success := False;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success := False;
config := TJsonObject.Create;
config.Strict := True;
success := config.LoadFile('onedrive-certificate-app.json');
if (success <> True) then
begin
WriteLn('Could not load private app configuration.');
Exit;
end;
if ((config.JsonTypeOf('tenant_id') <> 1) or (config.StringOfEquals('tenant_id','',True) = True)) then
begin
WriteLn('Expected a nonempty tenant_id in the JSON.');
Exit;
end;
if ((config.JsonTypeOf('client_id') <> 1) or (config.StringOfEquals('client_id','',True) = True)) then
begin
WriteLn('Expected a nonempty client_id in the JSON.');
Exit;
end;
if ((config.JsonTypeOf('user_id') <> 1) or (config.StringOfEquals('user_id','',True) = True)) then
begin
WriteLn('Expected a nonempty user_id in the JSON.');
Exit;
end;
if ((config.JsonTypeOf('pfx_path') <> 1) or (config.StringOfEquals('pfx_path','',True) = True)) then
begin
WriteLn('Expected a nonempty pfx_path in the JSON.');
Exit;
end;
// pfx_password may be empty for an unencrypted test PFX; protect the private key in production.
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(config.StringOf('tenant_id')));
tokenEndpoint.Append('/oauth2/v2.0/token');
tokenUrl := tokenEndpoint.GetAsString();
cert := TCert.Create;
success := cert.LoadPfxFile(config.StringOf('pfx_path'),config.StringOf('pfx_password'));
if (success <> True) then
begin
WriteLn('Could not load the application certificate.');
Exit;
end;
key := TPrivateKey.Create;
success := cert.GetPrivateKey(key);
if (success <> True) then
begin
WriteLn('The certificate needs an accessible RSA private key.');
Exit;
end;
der := TBinData.Create;
success := cert.ExportCertDerBd(der);
if (success <> True) then
begin
WriteLn('Could not read the certificate DER bytes.');
Exit;
end;
crypt := TCrypt2.Create;
crypt.HashAlgorithm := 'sha256';
crypt.EncodingMode := 'base64url';
thumbprint := crypt.HashBdENC(der);
if (crypt.LastMethodSuccess <> True) then
begin
WriteLn('Could not hash the certificate.');
Exit;
end;
header := TJsonObject.Create;
header.UpdateString('alg','PS256');
header.UpdateString('typ','JWT');
header.UpdateString('x5t#S256',thumbprint);
claims := TJsonObject.Create;
claims.UpdateString('aud',tokenUrl);
claims.UpdateString('iss',config.StringOf('client_id'));
claims.UpdateString('sub',config.StringOf('client_id'));
assertionId := crypt.GenerateUuid();
if (crypt.LastMethodSuccess <> True) then
begin
WriteLn('Could not create the assertion ID.');
Exit;
end;
claims.UpdateString('jti',assertionId);
clock := TCkDateTime.Create;
success := clock.SetFromCurrentSystemTime();
if (success <> True) then
begin
WriteLn('Could not read the clock.');
Exit;
end;
// Numeric dates are JSON numbers built from decimal strings, without converting timestamps to a platform-sized integer.
claims.UpdateNumber('iat',clock.GetAsUnixTimeStr(False));
claims.UpdateNumber('nbf',clock.GetAsUnixTimeStr(False));
success := clock.AddSeconds(300);
if (success <> True) then
begin
WriteLn('Could not set assertion expiry.');
Exit;
end;
claims.UpdateNumber('exp',clock.GetAsUnixTimeStr(False));
jwt := TJwt.Create;
assertion := jwt.CreateJwtPk(header.Emit(),claims.Emit(),key);
if (jwt.LastMethodSuccess <> True) then
begin
WriteLn('Could not sign the client assertion.');
Exit;
end;
req := THttpRequest.Create;
req.HttpVerb := 'POST';
req.ContentType := 'application/x-www-form-urlencoded';
req.AddParam('client_id',config.StringOf('client_id'));
req.AddParam('grant_type','client_credentials');
req.AddParam('scope','https://graph.microsoft.com/.default');
req.AddParam('client_assertion_type','urn:ietf:params:oauth:client-assertion-type:jwt-bearer');
req.AddParam('client_assertion',assertion);
resp := THttpResponse.Create;
result := TJsonObject.Create;
result.Strict := True;
success := http.HttpReq(tokenUrl,req,resp);
// A false result can still include an HTTP error response.
if ((success <> True) and (resp.StatusCode = 0)) then
begin
WriteLn('No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.');
Exit;
end;
if (resp.StatusCode <> 200) then
begin
WriteLn('Unexpected HTTP status: ' + resp.StatusCode);
WriteLn('Request ID: ' + resp.GetHeaderField('request-id'));
if (resp.StatusCode = 429) then
begin
WriteLn('Retry-After: ' + resp.GetHeaderField('Retry-After'));
end;
if (resp.StatusCode = 401) then
begin
WriteLn('Refresh the Graph access token or authorize again.');
end;
Exit;
end;
success := result.Load(resp.BodyStr);
if (success <> True) then
begin
WriteLn('Expected a well-formed JSON response.');
Exit;
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;
http.AuthToken := result.StringOf('access_token');
// Application access addresses a specific organizational user; /me is not available.
http.SetRequestHeader('Accept','application/json');
endpoint := TStringBuilder.Create;
endpoint.Append('https://graph.microsoft.com/v1.0/users/');
endpoint.Append(http.UrlEncode(config.StringOf('user_id')));
endpoint.Append('/drives?$select=id,name,driveType,quota&$top=50');
url := endpoint.GetAsString();
nextLink := TStringBuilder.Create;
seenLinks := TStringArray.Create;
pageCount := 0;
while ((url <> '') and (pageCount < 100)) do
begin
nextLink.SetString(url);
if (nextLink.StartsWith('https://graph.microsoft.com/v1.0/',True) <> True) then
begin
WriteLn('Unexpected pagination host or API version; no request sent.');
Exit;
end;
if (seenLinks.Find(url,0) >= 0) then
begin
WriteLn('Repeated pagination URL; stopping.');
Exit;
end;
seenLinks.Append(url);
success := http.HttpNoBody('GET',url,resp);
if ((success <> True) and (resp.StatusCode = 0)) then
begin
WriteLn('No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.');
Exit;
end;
if ((resp.StatusCode <> 200)) then
begin
WriteLn('Unexpected HTTP status: ' + resp.StatusCode);
WriteLn('Request ID: ' + resp.GetHeaderField('request-id'));
if (resp.StatusCode = 429) then
begin
WriteLn('Retry-After: ' + resp.GetHeaderField('Retry-After'));
end;
Exit;
end;
success := result.Load(resp.BodyStr);
if (success <> True) then
begin
WriteLn('Expected a well-formed JSON response.');
Exit;
end;
if (result.JsonTypeOf('value') <> 4) then
begin
WriteLn('Expected a value array.');
Exit;
end;
i := 0;
while (i < result.SizeOfArray('value')) do
begin
result.I := i;
if ((result.JsonTypeOf('value[i].id') <> 1) or (result.StringOfEquals('value[i].id','',True) = True)) then
begin
WriteLn('Expected a nonempty value[i].id in the JSON.');
Exit;
end;
WriteLn('Drive ID: ' + result.StringOf('value[i].id'));
WriteLn('Name: ' + result.StringOf('value[i].name'));
WriteLn('Drive type: ' + result.StringOf('value[i].driveType'));
// Quota values can be larger than int. Missing quota fields are not zero.
if (result.HasMember('value[i].quota.total') = True) then
begin
WriteLn('Total bytes: ' + result.StringOf('value[i].quota.total'));
WriteLn('Remaining bytes: ' + result.StringOf('value[i].quota.remaining'));
end;
i := i + 1;
end;
pageCount := pageCount + 1;
// A quoted JSON path treats the period in @odata.nextLink literally.
nextType := result.JsonTypeOf('"@odata.nextLink"');
if ((nextType = -1) or (nextType = 6)) then
begin
url := '';
end
else
begin
if ((nextType <> 1) or (result.StringOfEquals('"@odata.nextLink"','',True) = True)) then
begin
WriteLn('Invalid continuation link; cannot establish completeness.');
Exit;
end;
url := result.StringOf('"@odata.nextLink"');
end;
end;
if (url <> '') then
begin
WriteLn('Stopped at the example''s 100-page limit; save the continuation privately to resume.');
Exit;
end;
WriteLn('Completed pages: ' + pageCount);
config.Free;
http.Free;
tokenEndpoint.Free;
cert.Free;
key.Free;
der.Free;
crypt.Free;
header.Free;
claims.Free;
clock.Free;
jwt.Free;
req.Free;
resp.Free;
result.Free;
endpoint.Free;
nextLink.Free;
seenLinks.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.