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

Box: Refresh and Save Rotated OAuth Tokens

See more Box Examples

Refresh the user token saved by the authorization example. Box refresh tokens are single-use and expire after 60 days. Serialize refreshes for a token pair and save the replacement immediately; do not run concurrent refresh jobs.

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

Chilkat Lua Downloads

Lua
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 tokens = chilkat.JsonObject.new()
success = tokens:load_file("qa_data/tokens/box_oauth.json")
if not success then
    print(tokens.last_error_text)
    return
end

local oauth2 = chilkat.OAuth2.new()
oauth2.token_endpoint = "https://api.box.com/oauth2/token"
oauth2.client_id = "BOX_CLIENT_ID"
oauth2.client_secret = "BOX_CLIENT_SECRET"
oauth2.refresh_token = tokens:string_of("refresh_token")
success = oauth2:refresh_access_token()
if not success then
    print(oauth2.last_error_text)
    return
end

success = tokens:load(oauth2.access_token_response)
if not success then
    print(tokens.last_error_text)
    return
end

-- The previous refresh token is now invalid. Preserve this response even if
-- your normal token-store write fails. Do not retry with the old refresh token.
success = tokens:write_file("qa_data/tokens/box_oauth.json")
if not success then
    print(tokens.last_error_text)
    return
end

print("New access and refresh tokens saved. Do not log their values.")