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

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 Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

#  Requires Chilkat 11.5.0 or later and a previously unlocked Chilkat bundle.
#  See Global Unlock Sample.
#  Guide: Box API Guide.

set success 0

set oauth2 [new_CkOAuth2]

CkOAuth2_put_ListenPort $oauth2 3017
CkOAuth2_put_AuthorizationEndpoint $oauth2 "https://account.box.com/api/oauth2/authorize"
CkOAuth2_put_TokenEndpoint $oauth2 "https://api.box.com/oauth2/token"
CkOAuth2_put_ClientId $oauth2 "BOX_CLIENT_ID"
CkOAuth2_put_ClientSecret $oauth2 "BOX_CLIENT_SECRET"
#  Use Box's documented confidential-client authorization-code flow.
CkOAuth2_put_CodeChallenge $oauth2 0
set url [CkOAuth2_startAuth $oauth2]
if {[CkOAuth2_get_LastMethodSuccess $oauth2] != 1} then {
    puts [CkOAuth2_lastErrorText $oauth2]
    delete_CkOAuth2 $oauth2
    exit
}

set success [CkOAuth2_LaunchBrowser $oauth2 $url]
if {$success != 1} then {
    puts [CkOAuth2_lastErrorText $oauth2]
    delete_CkOAuth2 $oauth2
    exit
}

set elapsedMs 0
while {expr [$elapsedMs < 120000]  &&  [[CkOAuth2_get_AuthFlowState $oauth2] < 3]} {
    CkOAuth2_SleepMs $oauth2 100
    set elapsedMs [expr $elapsedMs + 100]
}
if {[CkOAuth2_get_AuthFlowState $oauth2] < 3} then {
    CkOAuth2_Cancel $oauth2
    puts "Authorization timed out."
    delete_CkOAuth2 $oauth2
    exit
}

if {[CkOAuth2_get_AuthFlowState $oauth2] != 3} then {
    puts "Authorization was denied or failed. State: [CkOAuth2_get_AuthFlowState $oauth2]"
    delete_CkOAuth2 $oauth2
    exit
}

#  Retain both tokens in your application's protected token store.
#  The variables below are deliberately not printed.
set accessToken [CkOAuth2_accessToken $oauth2]
set refreshToken [CkOAuth2_refreshToken $oauth2]
#  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.
set tokens [new_CkJsonObject]

set success [CkJsonObject_Load $tokens [CkOAuth2_accessTokenResponse $oauth2]]
if {$success != 1} then {
    puts [CkJsonObject_lastErrorText $tokens]
    delete_CkOAuth2 $oauth2
    delete_CkJsonObject $tokens
    exit
}

set success [CkJsonObject_WriteFile $tokens "qa_data/tokens/box_oauth.json"]
if {$success != 1} then {
    puts [CkJsonObject_lastErrorText $tokens]
    delete_CkOAuth2 $oauth2
    delete_CkJsonObject $tokens
    exit
}

puts "Authorization complete; token response saved in the protected local token file."

delete_CkOAuth2 $oauth2
delete_CkJsonObject $tokens