Sample code for 30+ languages & platforms
Objective-C Requires Chilkat v11.6.0+

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.

Microsoft documentation

Chilkat Objective-C Downloads

Objective-C
#import <CkoJsonObject.h>
#import <CkoHttp.h>
#import <CkoStringBuilder.h>
#import <NSString.h>
#import <CkoCert.h>
#import <CkoPrivateKey.h>
#import <CkoBinData.h>
#import <CkoCrypt2.h>
#import <CkoDateTime.h>
#import <CkoJwt.h>
#import <CkoHttpRequest.h>
#import <CkoHttpResponse.h>
#import <CkoHashtable.h>

BOOL success = NO;

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
success = NO;
CkoJsonObject *config = [[CkoJsonObject alloc] init];
config.Strict = YES;
success = [config LoadFile: @"onedrive-certificate-app.json"];
if (success != YES) {
    NSLog(@"%@",@"Could not load private app configuration.");
    return;
}

if (([[config JsonTypeOf: @"tenant_id"] intValue] != 1) || ([config StringOfEquals: @"tenant_id" value: @"" caseSensitive: YES] == YES)) {
    NSLog(@"%@",@"Expected a nonempty tenant_id in the JSON.");
    return;
}

if (([[config JsonTypeOf: @"client_id"] intValue] != 1) || ([config StringOfEquals: @"client_id" value: @"" caseSensitive: YES] == YES)) {
    NSLog(@"%@",@"Expected a nonempty client_id in the JSON.");
    return;
}

if (([[config JsonTypeOf: @"user_id"] intValue] != 1) || ([config StringOfEquals: @"user_id" value: @"" caseSensitive: YES] == YES)) {
    NSLog(@"%@",@"Expected a nonempty user_id in the JSON.");
    return;
}

if (([[config JsonTypeOf: @"pfx_path"] intValue] != 1) || ([config StringOfEquals: @"pfx_path" value: @"" caseSensitive: YES] == YES)) {
    NSLog(@"%@",@"Expected a nonempty pfx_path in the JSON.");
    return;
}

//  pfx_password may be empty for an unencrypted test PFX; protect the private key in production.
CkoHttp *http = [[CkoHttp alloc] init];
http.RequireSslCertVerify = YES;
http.FollowRedirects = NO;
http.ConnectTimeout = [NSNumber numberWithInt:20];
http.ReadTimeout = [NSNumber numberWithInt:30];
CkoStringBuilder *tokenEndpoint = [[CkoStringBuilder alloc] init];
[tokenEndpoint Append: @"https://login.microsoftonline.com/"];
[tokenEndpoint Append: [http UrlEncode: [config StringOf: @"tenant_id"]]];
[tokenEndpoint Append: @"/oauth2/v2.0/token"];
NSString *tokenUrl = [tokenEndpoint GetAsString];
CkoCert *cert = [[CkoCert alloc] init];
success = [cert LoadPfxFile: [config StringOf: @"pfx_path"] password: [config StringOf: @"pfx_password"]];
if (success != YES) {
    NSLog(@"%@",@"Could not load the application certificate.");
    return;
}

CkoPrivateKey *key = [[CkoPrivateKey alloc] init];
success = [cert GetPrivateKey: key];
if (success != YES) {
    NSLog(@"%@",@"The certificate needs an accessible RSA private key.");
    return;
}

CkoBinData *der = [[CkoBinData alloc] init];
success = [cert ExportCertDerBd: der];
if (success != YES) {
    NSLog(@"%@",@"Could not read the certificate DER bytes.");
    return;
}

CkoCrypt2 *crypt = [[CkoCrypt2 alloc] init];
crypt.HashAlgorithm = @"sha256";
crypt.EncodingMode = @"base64url";
NSString *thumbprint = [crypt HashBdENC: der];
if (crypt.LastMethodSuccess != YES) {
    NSLog(@"%@",@"Could not hash the certificate.");
    return;
}

CkoJsonObject *header = [[CkoJsonObject alloc] init];
[header UpdateString: @"alg" value: @"PS256"];
[header UpdateString: @"typ" value: @"JWT"];
[header UpdateString: @"x5t#S256" value: thumbprint];
CkoJsonObject *claims = [[CkoJsonObject alloc] init];
[claims UpdateString: @"aud" value: tokenUrl];
[claims UpdateString: @"iss" value: [config StringOf: @"client_id"]];
[claims UpdateString: @"sub" value: [config StringOf: @"client_id"]];
NSString *assertionId = [crypt GenerateUuid];
if (crypt.LastMethodSuccess != YES) {
    NSLog(@"%@",@"Could not create the assertion ID.");
    return;
}

[claims UpdateString: @"jti" value: assertionId];
CkoDateTime *clock = [[CkoDateTime alloc] init];
success = [clock SetFromCurrentSystemTime];
if (success != YES) {
    NSLog(@"%@",@"Could not read the clock.");
    return;
}

//  Numeric dates are JSON numbers built from decimal strings, without converting timestamps to a platform-sized integer.
[claims UpdateNumber: @"iat" numericStr: [clock GetAsUnixTimeStr: NO]];
[claims UpdateNumber: @"nbf" numericStr: [clock GetAsUnixTimeStr: NO]];
success = [clock AddSeconds: [NSNumber numberWithInt: 300]];
if (success != YES) {
    NSLog(@"%@",@"Could not set assertion expiry.");
    return;
}

[claims UpdateNumber: @"exp" numericStr: [clock GetAsUnixTimeStr: NO]];
CkoJwt *jwt = [[CkoJwt alloc] init];
NSString *assertion = [jwt CreateJwtPk: [header Emit] payload: [claims Emit] key: key];
if (jwt.LastMethodSuccess != YES) {
    NSLog(@"%@",@"Could not sign the client assertion.");
    return;
}

CkoHttpRequest *req = [[CkoHttpRequest alloc] init];
req.HttpVerb = @"POST";
req.ContentType = @"application/x-www-form-urlencoded";
[req AddParam: @"client_id" value: [config StringOf: @"client_id"]];
[req AddParam: @"grant_type" value: @"client_credentials"];
[req AddParam: @"scope" value: @"https://graph.microsoft.com/.default"];
[req AddParam: @"client_assertion_type" value: @"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"];
[req AddParam: @"client_assertion" value: assertion];
CkoHttpResponse *resp = [[CkoHttpResponse alloc] init];
CkoJsonObject *result = [[CkoJsonObject alloc] init];
result.Strict = YES;
success = [http HttpReq: tokenUrl request: req response: resp];
//  A false result can still include an HTTP error response.
if ((success != YES) && ([resp.StatusCode intValue] == 0)) {
    NSLog(@"%@",@"No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.");
    return;
}

if ([resp.StatusCode intValue] != 200) {
    NSLog(@"%@%d",@"Unexpected HTTP status: ",[resp.StatusCode intValue]);
    NSLog(@"%@%@",@"Request ID: ",[resp GetHeaderField: @"request-id"]);
    if ([resp.StatusCode intValue] == 429) {
        NSLog(@"%@%@",@"Retry-After: ",[resp GetHeaderField: @"Retry-After"]);
    }

    if ([resp.StatusCode intValue] == 401) {
        NSLog(@"%@",@"Refresh the Graph access token or authorize again.");
    }

    return;
}

success = [result Load: resp.BodyStr];
if (success != YES) {
    NSLog(@"%@",@"Expected a well-formed JSON response.");
    return;
}

if (([[result JsonTypeOf: @"access_token"] intValue] != 1) || ([result StringOfEquals: @"access_token" value: @"" caseSensitive: YES] == YES)) {
    NSLog(@"%@",@"Expected a nonempty access_token in the JSON.");
    return;
}

http.AuthToken = [result StringOf: @"access_token"];
//  Application access addresses a specific organizational user; /me is not available.
[http SetRequestHeader: @"Accept" value: @"application/json"];
CkoStringBuilder *endpoint = [[CkoStringBuilder alloc] init];
[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"];
NSString *url = [endpoint GetAsString];
CkoStringBuilder *nextLink = [[CkoStringBuilder alloc] init];
CkoHashtable *seenLinks = [[CkoHashtable alloc] init];
int pageCount = 0;
while (((url != @"") && (pageCount < 100))) {
    [nextLink SetString: url];
    if ([nextLink StartsWith: @"https://graph.microsoft.com/v1.0/" caseSensitive: YES] != YES) {
        NSLog(@"%@",@"Unexpected pagination host or API version; no request sent.");
        return;
    }

    if ([seenLinks Contains: url] == YES) {
        NSLog(@"%@",@"Repeated pagination URL; stopping.");
        return;
    }

    [seenLinks AddInt: url value: [NSNumber numberWithInt: 1]];
    success = [http HttpNoBody: @"GET" url: url response: resp];
    if ((success != YES) && ([resp.StatusCode intValue] == 0)) {
        NSLog(@"%@",@"No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.");
        return;
    }

    if (([resp.StatusCode intValue] != 200)) {
        NSLog(@"%@%d",@"Unexpected HTTP status: ",[resp.StatusCode intValue]);
        NSLog(@"%@%@",@"Request ID: ",[resp GetHeaderField: @"request-id"]);
        if ([resp.StatusCode intValue] == 429) {
            NSLog(@"%@%@",@"Retry-After: ",[resp GetHeaderField: @"Retry-After"]);
        }

        return;
    }

    success = [result Load: resp.BodyStr];
    if (success != YES) {
        NSLog(@"%@",@"Expected a well-formed JSON response.");
        return;
    }

    if ([[result JsonTypeOf: @"value"] intValue] != 4) {
        NSLog(@"%@",@"Expected a value array.");
        return;
    }

    int i = 0;
    while ((i < [[result SizeOfArray: @"value"] intValue])) {
        result.I = [NSNumber numberWithInt: i];
        if (([[result JsonTypeOf: @"value[i].id"] intValue] != 1) || ([result StringOfEquals: @"value[i].id" value: @"" caseSensitive: YES] == YES)) {
            NSLog(@"%@",@"Expected a nonempty value[i].id in the JSON.");
            return;
        }

        NSLog(@"%@%@",@"Drive ID: ",[result StringOf: @"value[i].id"]);
        NSLog(@"%@%@",@"Name: ",[result StringOf: @"value[i].name"]);
        NSLog(@"%@%@",@"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"] == YES) {
            NSLog(@"%@%@",@"Total bytes: ",[result StringOf: @"value[i].quota.total"]);
            NSLog(@"%@%@",@"Remaining bytes: ",[result StringOf: @"value[i].quota.remaining"]);
        }

        i = i + 1;
    }

    pageCount = pageCount + 1;
    //  A quoted JSON path treats the period in @odata.nextLink literally.
    int nextType = [[result JsonTypeOf: @"\"@odata.nextLink\""] intValue];
    if ((nextType == -1) || (nextType == 6)) {
        url = @"";
    }
    else {
        if ((nextType != 1) || ([result StringOfEquals: @"\"@odata.nextLink\"" value: @"" caseSensitive: YES] == YES)) {
            NSLog(@"%@",@"Invalid continuation link; cannot establish completeness.");
            return;
        }

        url = [result StringOf: @"\"@odata.nextLink\""];
    }

}

if (url != @"") {
    NSLog(@"%@",@"Stopped at the example's 100-page limit; save the continuation privately to resume.");
    return;
}

NSLog(@"%@%d",@"Completed pages: ",pageCount);