Lua Requires Chilkat v11.5.0+
Lua
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 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 oauth2 = chilkat.OAuth2.new()
oauth2.listen_port = 3017
oauth2.authorization_endpoint = "https://account.box.com/api/oauth2/authorize"
oauth2.token_endpoint = "https://api.box.com/oauth2/token"
oauth2.client_id = "BOX_CLIENT_ID"
oauth2.client_secret = "BOX_CLIENT_SECRET"
-- Use Box's documented confidential-client authorization-code flow.
oauth2.code_challenge = false
local url = oauth2:start_auth()
if not oauth2.last_method_success then
print(oauth2.last_error_text)
return
end
success = oauth2:launch_browser(url)
if not success then
print(oauth2.last_error_text)
return
end
local elapsedMs = 0
while (elapsedMs < 120000) and (oauth2.auth_flow_state < 3) do
oauth2:sleep_ms(100)
elapsedMs = elapsedMs + 100
end
if oauth2.auth_flow_state < 3 then
oauth2:cancel()
print("Authorization timed out.")
return
end
if oauth2.auth_flow_state ~= 3 then
print("Authorization was denied or failed. State: " .. oauth2.auth_flow_state)
return
end
-- Retain both tokens in your application's protected token store.
-- The variables below are deliberately not printed.
local accessToken = oauth2.access_token
local refreshToken = oauth2.refresh_token
-- 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.
local tokens = chilkat.JsonObject.new()
success = tokens:load(oauth2.access_token_response)
if not success then
print(tokens.last_error_text)
return
end
success = tokens:write_file("qa_data/tokens/box_oauth.json")
if not success then
print(tokens.last_error_text)
return
end
print("Authorization complete; token response saved in the protected local token file.")