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

OneDrive: Authorize with OAuth2 and PKCE

See more OneDrive Examples

Register a Microsoft Entra application for the intended personal Microsoft accounts and/or Microsoft 365 work/school accounts. The current Microsoft identity platform v2 endpoints serve both; the old distinction between separate providers is obsolete. Add http://localhost:3017/ as a Mobile and desktop applications redirect URI. Chilkat receives the loopback callback, so no hosted web server is required.

A public client uses PKCE (S256) without a client secret. Use common, consumers, organizations, or a tenant-specific authority consistently for both endpoints according to your app registration. Request offline_access and the file scopes required by the application; this example uses Files.ReadWrite. It does not request unrelated profile-write permission.

The private qa_data/tokens/oneDrive.json cache contains access_token, refresh_token, expires_in, and obtained_at. Refresh before expiration with the same client ID/authority, save rotated refresh tokens, and handle revocation or interaction requirements with a new sign-in. Tokens are not printed. Use protected, atomic storage per app/account in production. Web and mobile apps need redirect handling suited to their environment.

Permission: Delegated Files.ReadWrite; offline_access for refresh.

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 Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = false
    let oauth = CkoOAuth2()!
    //  Register a Mobile and desktop applications redirect URI: http://localhost:3017/
    //  Use an account type that matches your app registration (common, consumers, or tenant ID).
    oauth.authorizationEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
    oauth.tokenEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
    oauth.clientId = "YOUR_APPLICATION_CLIENT_ID"
    //  Public desktop applications cannot keep a client secret. Use PKCE instead.
    oauth.localHost = "localhost"
    oauth.listenPort = 3017
    oauth.codeChallenge = true
    oauth.codeChallengeMethod = "S256"
    //  Files.ReadWrite covers this collection. Use Files.Read for read-only operations.
    oauth.scope = "offline_access https://graph.microsoft.com/Files.ReadWrite"
    success = oauth.addAuthQueryParam(name: "prompt", value: "select_account")
    if success != true {
        print("Could not configure the authorization request.")
        return
    }

    var authUrl: String? = oauth.startAuth()
    if oauth.lastMethodSuccess != true {
        print("Could not start the local authorization listener.")
        return
    }

    success = oauth.launchBrowser(url: authUrl)
    if success != true {
        oauth.cancel()
        print("Could not open the system browser.")
        return
    }

    var waited: Int = 0
    while ((oauth.authFlowState.intValue < 3) && (waited < 180000)) {
        oauth.sleepMs(millisec: 200)
        waited = waited + 200
    }

    if oauth.authFlowState.intValue < 3 {
        oauth.cancel()
        print("Authorization timed out.")
        return
    }

    if oauth.authFlowState.intValue != 3 {
        print("Authorization did not complete. Flow state: \(oauth.authFlowState.intValue)")
        return
    }

    let token = CkoJsonObject()!
    token.strict = true
    success = token.load(json: oauth.accessTokenResponse)
    if success != true {
        print("Could not parse the token response; existing cache unchanged.")
        return
    }

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

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

    if (token.jsonType(of: "expires_in").intValue != 2) || (token.int(of: "expires_in").intValue <= 0) {
        print("Expected a positive access-token lifetime.")
        return
    }

    let obtained = CkoDateTime()!
    success = obtained.setFromCurrentSystemTime()
    if success != true {
        print("Could not record the token acquisition time.")
        return
    }

    token.updateString(jsonPath: "obtained_at", value: obtained.get(asTimestamp: false))
    //  This file contains credentials. Choose an access-controlled directory for the signed-in account.
    let fac = CkoFileAccess()!
    success = fac.dirEnsureExists(dirPath: "qa_data/tokens")
    if success != true {
        print("Could not create the private token-cache directory.")
        return
    }

    success = token.writeFile(path: "qa_data/tokens/oneDrive.json")
    if success != true {
        print("Could not save the token cache.")
        return
    }

    //  Never print access_token, refresh_token, or the complete token response.
    print("OneDrive authorization completed; token cache saved.")

}