Sample code for 30+ languages & platforms
Xbase++ 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 Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oOauth2
LOCAL cUrl
LOCAL nElapsedMs
LOCAL cAccessToken
LOCAL cRefreshToken
LOCAL oTokens

nSuccess := 0

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

nSuccess := 0

oOauth2 := CreateObject("Chilkat.OAuth2")
oOauth2:ListenPort := 3017
oOauth2:AuthorizationEndpoint := "https://account.box.com/api/oauth2/authorize"
oOauth2:TokenEndpoint := "https://api.box.com/oauth2/token"
oOauth2:ClientId := "BOX_CLIENT_ID"
oOauth2:ClientSecret := "BOX_CLIENT_SECRET"
//  Use Box's documented confidential-client authorization-code flow.
oOauth2:CodeChallenge := 0
cUrl := oOauth2:StartAuth()
IF (oOauth2:LastMethodSuccess != 1)
    ? oOauth2:LastErrorText
    oOauth2:destroy()
    RETURN
ENDIF

nSuccess := oOauth2:LaunchBrowser(cUrl)
IF (nSuccess != 1)
    ? oOauth2:LastErrorText
    oOauth2:destroy()
    RETURN
ENDIF

nElapsedMs := 0
DO WHILE (nElapsedMs < 120000) .AND. (oOauth2:AuthFlowState < 3)
    oOauth2:SleepMs(100)
    nElapsedMs := nElapsedMs + 100
ENDDO
IF (oOauth2:AuthFlowState < 3)
    oOauth2:Cancel()
    ? "Authorization timed out."
    oOauth2:destroy()
    RETURN
ENDIF

IF (oOauth2:AuthFlowState != 3)
    ? "Authorization was denied or failed. State: " + Str(oOauth2:AuthFlowState)
    oOauth2:destroy()
    RETURN
ENDIF

//  Retain both tokens in your application's protected token store.
//  The variables below are deliberately not printed.
cAccessToken := oOauth2:AccessToken
cRefreshToken := oOauth2:RefreshToken
//  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.
oTokens := CreateObject("Chilkat.JsonObject")
nSuccess := oTokens:Load(oOauth2:AccessTokenResponse)
IF (nSuccess != 1)
    ? oTokens:LastErrorText
    oOauth2:destroy()
    oTokens:destroy()
    RETURN
ENDIF

nSuccess := oTokens:WriteFile("qa_data/tokens/box_oauth.json")
IF (nSuccess != 1)
    ? oTokens:LastErrorText
    oOauth2:destroy()
    oTokens:destroy()
    RETURN
ENDIF

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

oOauth2:destroy()
oTokens:destroy()