Lua Requires Chilkat v11.5.0+
Lua
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 Lua Downloads
local chilkat = require("chilkat")
-- Requires Chilkat 11.5.0 or later and a previously unlocked Chilkat bundle.
-- See Global Unlock Sample.
-- Guide: Box API Guide.
local success = false
local config = chilkat.JsonObject.new()
success = config:load_file("qa_data/tokens/box_jwt_config.json")
if not success then
print(config.last_error_text)
return
end
local key = chilkat.PrivateKey.new()
success = key:load_encrypted_pem(config:string_of("boxAppSettings.appAuth.privateKey"), config:string_of("boxAppSettings.appAuth.passphrase"))
if not success then
print(key.last_error_text)
return
end
local header = chilkat.JsonObject.new()
header:update_string("alg", "RS256")
header:update_string("typ", "JWT")
header:update_string("kid", config:string_of("boxAppSettings.appAuth.publicKeyID"))
local jwt = chilkat.Jwt.new()
local prng = chilkat.Prng.new()
local nonce = prng:gen_random(32, "hex")
if not prng.last_method_success then
print(prng.last_error_text)
return
end
local claims = chilkat.JsonObject.new()
claims:update_string("iss", config:string_of("boxAppSettings.clientID"))
claims:update_string("sub", config:string_of("enterpriseID"))
claims:update_string("box_sub_type", "enterprise")
claims:update_string("aud", "https://api.box.com/oauth2/token")
claims:update_string("jti", nonce)
claims:update_int("exp", jwt:gen_numeric_date(45))
local assertion = jwt:create_jwt_pk(header:emit(), claims:emit(), key)
if not jwt.last_method_success then
print(jwt.last_error_text)
return
end
local curl = chilkat.HttpCurl.new()
curl:set_var("client_id", config:string_of("boxAppSettings.clientID"))
curl:set_var("client_secret", config:string_of("boxAppSettings.clientSecret"))
curl:set_var("assertion", assertion)
curl:clear_target_output("*")
curl:clear_var("access_token")
curl:add_target_output("access_token", "access_token")
success = curl:do_your_thing("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 (not success) or (curl.status_code ~= 200) then
print("Box request failed. HTTP status: " .. curl.status_code)
print("Failure reason: " .. curl.fail_reason)
return
end
if not curl:var_defined("!") then
print("Expected response fields are missing.")
return
end
-- 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.")