Sample code for 30+ languages & platforms
Swift Requires Chilkat v11.6.0+

Outlook Calendar: Access a Microsoft 365 Calendar with a Certificate

See more Outlook Calendar Examples

Obtain an app-only Graph token using a signed certificate assertion, then read an explicitly named Microsoft 365 mailbox's default calendar. Upload the public certificate to the Entra app registration and keep its RSA private key private. Grant the appropriate Graph application permission and administrator consent: Calendars.ReadBasic for this read, or a stronger permission only for the operations required. Scope mailbox access using your organization's supported Exchange application-access controls/RBAC; avoid unintended tenant-wide access.

Private outlook-calendar-app.json contains tenant_id (the directory ID), client_id (Application ID), mailbox (object ID or UPN), pfx_path, and pfx_password. Use an organization tenant, not common/consumers. This is not available for personal Outlook.com mailboxes. Certificate authentication is not a requirement to run a public web server, but the private key must remain in a trusted application environment.

The short-lived assertion uses PS256 and an x5t#S256 thumbprint of the certificate's DER bytes. It is a credential submitted only to the token endpoint, not the Graph bearer token. Client credentials returns no refresh token: obtain another access token with a fresh assertion when needed. The example never prints tokens or assertions.

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 calendar data private.

Microsoft documentation

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = false
    let config = CkoJsonObject()!
    config.strict = true
    success = config.loadFile(path: "outlook-calendar-app.json")
    if success != true {
        print("Could not load private app configuration.")
        return
    }

    if (config.jsonType(of: "tenant_id").intValue != 1) || (config.string(ofEquals: "tenant_id", value: "", caseSensitive: true) == true) {
        print("Expected a nonempty tenant_id in the JSON.")
        return
    }

    if (config.jsonType(of: "client_id").intValue != 1) || (config.string(ofEquals: "client_id", value: "", caseSensitive: true) == true) {
        print("Expected a nonempty client_id in the JSON.")
        return
    }

    if (config.jsonType(of: "mailbox").intValue != 1) || (config.string(ofEquals: "mailbox", value: "", caseSensitive: true) == true) {
        print("Expected a nonempty mailbox in the JSON.")
        return
    }

    if (config.jsonType(of: "pfx_path").intValue != 1) || (config.string(ofEquals: "pfx_path", value: "", caseSensitive: true) == true) {
        print("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.
    let http = CkoHttp()!
    http.requireSslCertVerify = true
    http.followRedirects = false
    http.connectTimeout = 20
    http.readTimeout = 30
    let tokenEndpoint = CkoStringBuilder()!
    tokenEndpoint.append(value: "https://login.microsoftonline.com/")
    tokenEndpoint.append(value: http.urlEncode(str: config.string(of: "tenant_id")))
    tokenEndpoint.append(value: "/oauth2/v2.0/token")
    var tokenUrl: String? = tokenEndpoint.getAsString()
    let cert = CkoCert()!
    success = cert.loadPfxFile(path: config.string(of: "pfx_path"), password: config.string(of: "pfx_password"))
    if success != true {
        print("Could not load the application certificate.")
        return
    }

    let key = CkoPrivateKey()!
    success = cert.getPrivateKey(privKey: key)
    if success != true {
        print("The certificate needs an accessible RSA private key.")
        return
    }

    let der = CkoBinData()!
    success = cert.exportDerBd(cerData: der)
    if success != true {
        print("Could not read the certificate DER bytes.")
        return
    }

    let crypt = CkoCrypt2()!
    crypt.hashAlgorithm = "sha256"
    crypt.encodingMode = "base64url"
    var thumbprint: String? = crypt.hashBdENC(bd: der)
    if crypt.lastMethodSuccess != true {
        print("Could not hash the certificate.")
        return
    }

    let header = CkoJsonObject()!
    header.updateString(jsonPath: "alg", value: "PS256")
    header.updateString(jsonPath: "typ", value: "JWT")
    header.updateString(jsonPath: "x5t#S256", value: thumbprint)
    let claims = CkoJsonObject()!
    claims.updateString(jsonPath: "aud", value: tokenUrl)
    claims.updateString(jsonPath: "iss", value: config.string(of: "client_id"))
    claims.updateString(jsonPath: "sub", value: config.string(of: "client_id"))
    var assertionId: String? = crypt.generateUuid()
    if crypt.lastMethodSuccess != true {
        print("Could not create the assertion ID.")
        return
    }

    claims.updateString(jsonPath: "jti", value: assertionId)
    let clock = CkoDateTime()!
    success = clock.setFromCurrentSystemTime()
    if success != true {
        print("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(jsonPath: "iat", numericStr: clock.get(asUnixTimeStr: false))
    claims.updateNumber(jsonPath: "nbf", numericStr: clock.get(asUnixTimeStr: false))
    success = clock.addSeconds(numSeconds: 300)
    if success != true {
        print("Could not set assertion expiry.")
        return
    }

    claims.updateNumber(jsonPath: "exp", numericStr: clock.get(asUnixTimeStr: false))
    let jwt = CkoJwt()!
    var assertion: String? = jwt.createPk(header: header.emit(), payload: claims.emit(), key: key)
    if jwt.lastMethodSuccess != true {
        print("Could not sign the client assertion.")
        return
    }

    let req = CkoHttpRequest()!
    req.httpVerb = "POST"
    req.contentType = "application/x-www-form-urlencoded"
    req.addParam(name: "client_id", value: config.string(of: "client_id"))
    req.addParam(name: "grant_type", value: "client_credentials")
    req.addParam(name: "scope", value: "https://graph.microsoft.com/.default")
    req.addParam(name: "client_assertion_type", value: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
    req.addParam(name: "client_assertion", value: assertion)
    let resp = CkoHttpResponse()!
    let result = CkoJsonObject()!
    result.strict = true
    success = http.httpReq(url: tokenUrl, request: req, response: resp)
    //  A false result can still include an HTTP error response.
    if (success != true) && (resp.statusCode.intValue == 0) {
        print("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.")
        return
    }

    if resp.statusCode.intValue != 200 {
        print("Unexpected HTTP status: \(resp.statusCode.intValue)")
        print("Request ID: \(resp.getHeaderField(fieldName: "request-id")!)")
        if resp.statusCode.intValue == 429 {
            print("Retry-After: \(resp.getHeaderField(fieldName: "Retry-After")!)")
        }

        if resp.statusCode.intValue == 401 {
            print("Refresh the Graph access token or authorize again.")
        }

        return
    }

    success = result.load(json: resp.bodyStr)
    if success != true {
        print("Expected a well-formed JSON response.")
        return
    }

    if (result.jsonType(of: "access_token").intValue != 1) || (result.string(ofEquals: "access_token", value: "", caseSensitive: true) == true) {
        print("Expected a nonempty access_token in the JSON.")
        return
    }

    http.authToken = result.string(of: "access_token")
    //  App-only tokens have no /me. Address the approved mailbox explicitly.
    let endpoint = CkoStringBuilder()!
    endpoint.append(value: "https://graph.microsoft.com/v1.0/users/")
    endpoint.append(value: http.urlEncode(str: config.string(of: "mailbox")))
    endpoint.append(value: "/calendar?$select=id,name,canEdit")
    success = http.httpNoBody(verb: "GET", url: endpoint.getAsString(), response: resp)
    //  A false result can still include an HTTP error response.
    if (success != true) && (resp.statusCode.intValue == 0) {
        print("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.")
        return
    }

    if resp.statusCode.intValue != 200 {
        print("Unexpected HTTP status: \(resp.statusCode.intValue)")
        print("Request ID: \(resp.getHeaderField(fieldName: "request-id")!)")
        if resp.statusCode.intValue == 429 {
            print("Retry-After: \(resp.getHeaderField(fieldName: "Retry-After")!)")
        }

        if resp.statusCode.intValue == 401 {
            print("Refresh the Graph access token or authorize again.")
        }

        return
    }

    success = result.load(json: resp.bodyStr)
    if success != true {
        print("Expected a well-formed JSON response.")
        return
    }

    if (result.jsonType(of: "id").intValue != 1) || (result.string(ofEquals: "id", value: "", caseSensitive: true) == true) {
        print("Expected a nonempty id in the JSON.")
        return
    }

    print("Calendar ID: \(result.string(of: "id")!)")
    print("Calendar name: \(result.string(of: "name")!)")

}