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

Outlook Contacts: Access Microsoft 365 Contacts with a Certificate

See more Outlook Contact Examples

Authenticate an unattended application with an RSA certificate and read contacts in one explicitly named Microsoft 365 mailbox. Upload the public certificate to the Entra app registration, grant Graph application Contacts.Read permission and administrator consent, and restrict mailbox access using supported Exchange application-access controls. Use Contacts.ReadWrite only for operations that require writes. Personal Outlook.com accounts do not support this app-only flow.

Private outlook-contacts-app.json contains tenant_id (directory ID), client_id (Application ID), mailbox (object ID or UPN), pfx_path, and pfx_password. Use an organizational tenant rather than common or consumers. Protect the private key in an application environment you control.

A fresh five-minute PS256 assertion includes the SHA-256 certificate thumbprint in x5t#S256. The assertion authenticates only to the tenant token endpoint; the returned access token goes to Graph. The .default scope uses administrator-granted application permissions. There is no refresh token: obtain a new access token with a new assertion when needed.

Follow the complete @odata.nextLink and retain the immutable-ID preference. The code checks the host, rejects repeated continuations, and has a stated 100-page demonstration limit. Save a continuation privately to resume a larger scan. IDs are opaque strings, and names or email addresses are not unique identifiers.

HTTP methods can return false for an HTTP error as well as a connection failure. The code distinguishes those cases and checks the expected status before reading JSON. For 401, refresh the access token or authorize again; for 403, check permissions, mailbox access, and tenant policy. For 429, honor Retry-After before a bounded retry. Do not automatically repeat a write after an uncertain outcome. Keep detailed errors and contact data 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: @"outlook-contacts-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: @"mailbox"] intValue] != 1) || ([config StringOfEquals: @"mailbox" value: @"" caseSensitive: YES] == YES)) {
    NSLog(@"%@",@"Expected a nonempty mailbox 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 tokens address an explicitly authorized mailbox, never /me.
[http SetRequestHeader: @"Accept" value: @"application/json"];
[http SetRequestHeader: @"Prefer" value: @"IdType=\"ImmutableId\""];
CkoStringBuilder *endpoint = [[CkoStringBuilder alloc] init];
[endpoint Append: @"https://graph.microsoft.com/v1.0/users/"];
[endpoint Append: [http UrlEncode: [config StringOf: @"mailbox"]]];
[endpoint Append: @"/contacts?$select=id,displayName&$top=50"];
NSString *url = [endpoint GetAsString];
CkoStringBuilder *nextLink = [[CkoStringBuilder alloc] init];
CkoHashtable *seenLinks = [[CkoHashtable alloc] init];
int pageCount = 0;
while ((pageCount < 100)) {
    //  Use Microsoft's nextLink exactly as returned; do not rebuild skip tokens.
    [nextLink Clear];
    [nextLink Append: 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];
    //  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: @"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(@"%@%@",@"Contact ID: ",[result StringOf: @"value[i].id"]);
        NSLog(@"%@%@",@"Display name: ",[result StringOf: @"value[i].displayName"]);
        i = i + 1;
    }

    pageCount = pageCount + 1;
    //  Quote the member name because @odata.nextLink contains a literal period.
    int nextType = [[result JsonTypeOf: @"\"@odata.nextLink\""] intValue];
    if ((nextType == -1) || (nextType == 6)) {
        NSLog(@"%@%d",@"Completed pages: ",pageCount);
        return;
    }

    if ((nextType != 1) || ([result StringOfEquals: @"\"@odata.nextLink\"" value: @"" caseSensitive: YES] == YES)) {
        NSLog(@"%@",@"Invalid continuation link; cannot establish completeness.");
        return;
    }

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

NSLog(@"%@",@"Stopped at the example's 100-page limit. Save the continuation URL privately to resume.");