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

Box: Authorize a User with OAuth 2.0

See more Box Examples

Interactive local-development example using a browser and a loopback callback. Register exactly http://localhost:3017/ in the Box User app. Run this in a trusted environment that can hold the client secret. A deployed web app must handle its registered HTTPS callback on the server.

See the Box API guide for setup and the complete workflow.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  Requires Chilkat 11.5.0 or later and a previously unlocked Chilkat bundle.
    //  See Global Unlock Sample.
    //  Guide: Box API Guide.

    success = false

    let oauth2 = CkoOAuth2()!
    oauth2.listenPort = 3017
    oauth2.authorizationEndpoint = "https://account.box.com/api/oauth2/authorize"
    oauth2.tokenEndpoint = "https://api.box.com/oauth2/token"
    oauth2.clientId = "BOX_CLIENT_ID"
    oauth2.clientSecret = "BOX_CLIENT_SECRET"
    //  Use Box's documented confidential-client authorization-code flow.
    oauth2.codeChallenge = false
    var url: String? = oauth2.startAuth()
    if oauth2.lastMethodSuccess != true {
        print("\(oauth2.lastErrorText!)")
        return
    }

    success = oauth2.launchBrowser(url: url)
    if success != true {
        print("\(oauth2.lastErrorText!)")
        return
    }

    var elapsedMs: Int = 0
    while (elapsedMs < 120000) && (oauth2.authFlowState.intValue < 3) {
        oauth2.sleepMs(millisec: 100)
        elapsedMs = elapsedMs + 100
    }

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

    if oauth2.authFlowState.intValue != 3 {
        print("Authorization was denied or failed. State: \(oauth2.authFlowState.intValue)")
        return
    }

    //  Retain both tokens in your application's protected token store.
    //  The variables below are deliberately not printed.
    var accessToken: String? = oauth2.accessToken
    var refreshToken: String? = oauth2.refreshToken
    //  For this local-development example only, save in a directory restricted to this user.
    //  Create qa_data/tokens before running; never put this file under a web root.
    let tokens = CkoJsonObject()!
    success = tokens.load(json: oauth2.accessTokenResponse)
    if success != true {
        print("\(tokens.lastErrorText!)")
        return
    }

    success = tokens.writeFile(path: "qa_data/tokens/box_oauth.json")
    if success != true {
        print("\(tokens.lastErrorText!)")
        return
    }

    print("Authorization complete; token response saved in the protected local token file.")

}