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

Box: Get a Service Account Token with Client Credentials

See more Box Examples

Obtain a Box service-account token using the client credentials grant. Configure and authorize a Server app first. Load credentials from protected application configuration; do not ship a client secret in a public client.

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 curl = CkoHttpCurl()!
    curl.setVar(varName: "client_id", varValue: "BOX_CLIENT_ID")
    curl.setVar(varName: "client_secret", varValue: "BOX_CLIENT_SECRET")
    curl.setVar(varName: "enterprise_id", varValue: "BOX_ENTERPRISE_ID")
    //  enterprise identifies the app's service account. This is not an admin-user token.
    curl.clearTargetOutput(varName: "*")
    curl.clearVar(varName: "access_token")
    curl.addTargetOutput(jsonPath: "access_token", varName: "access_token")
    success = curl.doYourThing(targetCurl: "curl -X POST \"https://api.box.com/oauth2/token\" --data-urlencode \"grant_type=client_credentials\" --data-urlencode \"client_id={{client_id}}\" --data-urlencode \"client_secret={{client_secret}}\" --data-urlencode \"box_subject_type=enterprise\" --data-urlencode \"box_subject_id={{enterprise_id}}\"")
    if (success != true) || (curl.statusCode.intValue != 200) {
        print("Box request failed. HTTP status: \(curl.statusCode.intValue)")
        print("Failure reason: \(curl.failReason.intValue)")
        return
    }

    if curl.varDefined(varName: "!") != true {
        print("Expected response fields are missing.")
        return
    }

    //  Keep this token in protected application memory; reacquire it when it expires.
    //  Do not print tokens or the complete token response.
    print("Service-account access token obtained.")
    curl.clearTargetOutput(varName: "*")
    let authorizedCommand1 = CkoStringBuilder()!
    authorizedCommand1.setString(value: "curl -X GET \"https://api.box.com/2.0/users/me?fields=id,name,login\" -H \"Authorization: Bearer {{access_token}}\"")
    var headerReplacement1: Int = authorizedCommand1.replace(value: "{{access_token}}", replacement: curl.getVar(varName: "access_token")).intValue
    success = curl.doYourThing(targetCurl: authorizedCommand1.getAsString())
    if (success != true) || (curl.statusCode.intValue != 200) {
        print("Box request failed. HTTP status: \(curl.statusCode.intValue)")
        print("Failure reason: \(curl.failReason.intValue)")
        print("\(curl.responseBodyStr!)")
        return
    }

    print("\(curl.responseBodyStr!)")

}