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

Box: Get a Service Account Token with JWT

See more Box Examples

Use the encrypted private key in a Box application configuration file to sign a short-lived assertion and exchange it for an access token. Configure and authorize a JWT Server app first. The enterprise subject obtains the service-account token.

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 config = CkoJsonObject()!
    success = config.loadFile(path: "qa_data/tokens/box_jwt_config.json")
    if success != true {
        print("\(config.lastErrorText!)")
        return
    }

    let key = CkoPrivateKey()!
    success = key.loadEncryptedPem(pemStr: config.string(of: "boxAppSettings.appAuth.privateKey"), password: config.string(of: "boxAppSettings.appAuth.passphrase"))
    if success != true {
        print("\(key.lastErrorText!)")
        return
    }

    let header = CkoJsonObject()!
    header.updateString(jsonPath: "alg", value: "RS256")
    header.updateString(jsonPath: "typ", value: "JWT")
    header.updateString(jsonPath: "kid", value: config.string(of: "boxAppSettings.appAuth.publicKeyID"))
    let jwt = CkoJwt()!
    let prng = CkoPrng()!
    var nonce: String? = prng.genRandom(numBytes: 32, encoding: "hex")
    if prng.lastMethodSuccess != true {
        print("\(prng.lastErrorText!)")
        return
    }

    let claims = CkoJsonObject()!
    claims.updateString(jsonPath: "iss", value: config.string(of: "boxAppSettings.clientID"))
    claims.updateString(jsonPath: "sub", value: config.string(of: "enterpriseID"))
    claims.updateString(jsonPath: "box_sub_type", value: "enterprise")
    claims.updateString(jsonPath: "aud", value: "https://api.box.com/oauth2/token")
    claims.updateString(jsonPath: "jti", value: nonce)
    claims.updateInt(jsonPath: "exp", value: jwt.genNumericDate(numSecOffset: 45).intValue)
    var assertion: String? = jwt.createPk(header: header.emit(), payload: claims.emit(), key: key)
    if jwt.lastMethodSuccess != true {
        print("\(jwt.lastErrorText!)")
        return
    }

    let curl = CkoHttpCurl()!
    curl.setVar(varName: "client_id", varValue: config.string(of: "boxAppSettings.clientID"))
    curl.setVar(varName: "client_secret", varValue: config.string(of: "boxAppSettings.clientSecret"))
    curl.setVar(varName: "assertion", varValue: assertion)
    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=urn:ietf:params:oauth:grant-type:jwt-bearer\" --data-urlencode \"client_id={{client_id}}\" --data-urlencode \"client_secret={{client_secret}}\" --data-urlencode \"assertion={{assertion}}\"")
    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
    }

    //  Reuse the token in this HttpCurl instance. JWT tokens are renewed by making
    //  a new assertion/token request, not by using a refresh token.
    print("JWT access token obtained.")

}